an introduction to problem solving &...

30
JAVA An Introduction to Problem Solving & Programming Fourth Edition

Upload: doquynh

Post on 10-Apr-2018

221 views

Category:

Documents


4 download

TRANSCRIPT

JAVAAn Introduction to

Problem Solving & Programming

Fourth Edition

Thank you for purchasing a new copy of the best-selling Savitch Java book. The ravereviews on Amazon by readers attest to the user-friendly presentation for beginners.

You will now be able to access Prentice Hall’s free, web-based, programming envi-ronment called CodeKey. It is an on-line, interactive tutorial for readers learning how toprogram with the Java programming language. You will be able to complete selectedprogramming exercises from the text and receive automated feedback on your Java code.The on-line exercises will tell you how to improve your Java code when you modify exist-ing programs from the book. Code Key will allow you to “test” your programs before sub-mitting them for class assignments. You can use CodeKey for programming practice.

CodeKey will give hints on how to improve your code, and how to debug it when nec-essary. You will be alerted to errors, and will be given programming hints on how to fixthem.

You can access CodeKey at www.prenhall.com/codekey

JAVAAn Introduction to

Problem Solving & Programming

Fourth Edition

W A L T E R S A V I T C H

Upper Saddle River, NJ 07458

Library of Congress Cataloging-in-Publication Data

Savitch, Walter J.Java : an introduction to problem solving & programming / Walter Savitch.-- 4th ed.

p. cm.Includes bibliographical references and index.ISBN 0-13-149202-0 1. Java (Computer program language) I. Title.

QA76.73.J38S27 2005005.13'3--dc22

2004057347

Vice President and Editorial Director, ECS: Marcia HortonPublisher: Alan R. AptAssociate Editor: Toni D. HolmVice President and Director of Production and Manufacturing, ESM: David W. RiccardiExecutive Managing Editor: Vince O’BrienAssistant Managing Editor: Camille TrentacosteProduction Editor: Irwin ZuckerDirector of Creative Services: Paul BelfantiArt Director: Kenny BeckCover Designer: Laura GardnerArt Editor: Xiaohong ZhuManufacturing Manager: Trudy PisciottiManufacturing Buyer: Lisa McDowellMarketing Manager: Pamela HerspergerMarketing Assistant: Barrie Reinhold

©1999, 2001, 2004, 2005 by Pearson Education Inc.Pearson Prentice HallUpper Saddle River, NJ 07458

All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher.

The author and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The author and publisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained in this book. The author and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.

Printed in the United States of America10 9 8 7 6 5 4 3 2 1

ISBN 0-13-149202-0

Pearson Education Ltd., LondonPearson Education Australia Pty. Ltd., SydneyPearson Education Singapore, Pte. Ltd.Pearson Education North Asia Ltd., Hong KongPearson Education Canada, Inc., TorontoPearson Educación de Mexico, S.A. de C.V.Pearson Education—Japan, TokyoPearson Education Malaysia, Pte. Ltd.Pearson Education, Inc., Upper Saddle River, New Jersey

TRADEMARK INFORMATIONANSI is a registered trademark of American National Standards Institute.CodeWarrior is a registered trademark of Metrowerks, Inc.Java, Duke, and all Java based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.JBuilder and JBuilder Foundation are trademarks of Inprise/Borland.Mac, Macintosh, and MacOS are trademarks of Apple Computer, Inc.Netscape and Netscape Navigator are trademarks of Netscape Communications, Inc.TextPad is a trademark of Helios Software Solutions.UNIX is a trademark of UNIX System Laboratories.Windows, WindowsNT, and Internet Explorer are trademarks or registered trademarks of Microsoft Corporation.FrontPage (Microsoft Corportation)DreamWeaver (Maacromedia, Inc.)GoLive (Adobe Systems Inc.)

To Christina

FEATURES OF THIS TEXT

FAQProvides students answers to frequentlyasked questions within the context ofthe chapter.

GotchaHelps students identify possible

programming pitfalls.▲

Quick ReferenceProvides concise, user-friendly referencefor key programming concepts.

Java TipGives students helpful information about

the Java programming language.

RememberReinforces concepts presented in thechapter.

Graphics Supplement (Optional)Early optional graphics supplementscover GUIs built using both applets andthe JFrame class are integrated through-out the text. Advanced GUI chaptersgive additional graphics material.

Self-Test QuestionsProvides students the opportunity topractice skills learned in the chapter.

The whole is more than the sum of its parts. —Proverb

Now that we have explained methods and parameters more completely, we will revisitmaterial from the previous graphics supplements to explain a few things more completely.We will use methods to rewrite one of our previous graphics applets in a cleaner way, wewill explain the Graphics class more completely, and we will introduce some additionaldrawing methods. Finally, we introduce the method init, which is another applet methodsimilar to paint but used for different purposes.

4.4 GRAPHICS SUPPLEMENT (OPTIONAL)

Savitch4e_FeaturesppFMv2.qxp 11/12/04 8:10 PM Page 2

vii

PREFACE FOR INSTRUCTORSThis book is designed for a first course in programming and computer science. It coversprogramming techniques, as well as the basics of the Java programming language. It issuitable for courses as short as one quarter or as long as a full academic year. No previousprogramming experience is required, nor is any mathematics, other than a little highschool algebra. The book can also be used for a course designed to teach Java to studentswho have already had another programming course, in which case the first few chapterscan be assigned as outside reading.

This book uses only standard classes available as part of Java. No additional classesare needed.

All of the code in this book has been tested using Sun’s Java JDK version 5.0, beta2 release. To be fully compatible with this book, the Java used in your class should beversion 5.0 or higher.1

Changes in This EditionIf you have not used the third edition of this text, you can skip this subsection. If you haveused the third edition, this subsection will tell you how this fourth edition differs from thethird.

For instructors, the transition from the third to this fourth edition is easy. You can teachthe same course, presenting basically the same topics in the same order with only veryminor changes in the material covered. The largest required change is that this edition usesthe new Scanner class available in Java version 5.0 in place of the class SavichIn.2 Ifyou wish to change your course further, this edition includes Graphics Supplement sec-tions that allow you to (optionally) add early graphics coverage. This edition also addscoverage of generic programming with type parameters.

Chapter 1 through 9 each end with a Graphics Supplement section that covers graphicsapplications and GUIs using applets as well as JFrames. These Graphics Supplement sec-tions are optional. If you desire more material on graphics and GUIs then after Chapter 9(in fact any time after Chapter 7), you can skip ahead to Chapter 12, which starts thedetailed coverage of Swing.

The other major changes to this edition have to do with updating the text to match Javaversion 5.0: The new Scanner class is used for keyboard input. We explain and use auto-matic boxing and unboxing. The coverage of vectors has been updated to use generic typeparameters. An introduction to type parameters and generics is given in Chapter 10.

Latest Java CoverageThis edition has been updated to use the latest features of Java version 5.0. In particular,we use the new Scanner class for keyboard input, we cover and use automatic boxing and

1. Sun has changed the way it numbers versions. Version 5.0 was formerly called version 1.5 andyou may still find it referred to as version 1.5 in some contexts.

2. If you wish to use the class SavitchIn, it is available in an appendix, and the source code isavailable over the Web. However, SavitchIn is not used anywhere in the text.

viii Preface for Instructors

unboxing, we do vectors using type parameters, and we include an introduction to genericprogramming using type parameters. As we wrote this book, we checked all code usingSun’s beta 2 release of Java 5.0.

Flexibility

If you are an instructor, this book adapts to the way you tech, rather than making youadapt to the book. This book does not tightly prescribe the sequence in which your coursemust cover topics. You can easily change the order in which you cover chapters and sec-tions. The particulars about rearranging material are explained in the dependency chartthat follows this preface and in more detail in the “Prerequisites” section at the start ofeach chapter.

This book uses no specialized libraries. Only standard classes available as part of thestandard Java libraries are used.

Early GraphicsOptional Graphic Supplement sections end chapters starting with Chapter 1. This allowsyou the option of covering graphics and GUI programming from the start of your course.The Graphics Supplement sections emphasize applets but also cover GUIs built using theJFrame class. Any time after Chapter 7, you may move on to the main chapters on GUIprogramming (Chapters 12–14). Alternatively, the Graphics Supplement sections continuethrough Chapter 9, allowing you to continue with a mix of graphics and more traditionalprogramming. Instructors who prefer to postpone the coverage of graphics may postponeor skip the Graphics Supplement sections.

Coverage of Problem-Solving and Programming TechniquesThis book is designed to teach students basic problem-solving and programming tech-niques and is not simply a book about Java syntax. It contains numerous case studies andprogramming tips, as well as many sections that explain important problem-solving andprogramming techniques, such as loop design techniques, debugging techniques, styletechniques, abstract data types, and basic object-oriented programming techniques,including UML and event-driven programming, and generic programming using typeparameters.

Object-Oriented and Traditional TechniquesAny course that really teaches Java must teach classes early, since everything in Javainvolves classes. A Java program is a class. The data type for strings of characters is aclass. Even the behavior of the equals operator (==) depends on whether it is comparingobjects from classes or simpler data items. Classes cannot be avoided, except by means ofabsurdly long and complicated “magic formulas.” This book introduces classes fairlyearly. Some exposure to using classes is given in Chapters 1 and 2. Chapter 4 covers how

Preface for Instructors ix

to define classes. All of the basic information about classes, including inheritance, ispresented by the end of Chapter 7 (even if you omit Chapter 6). However, some topicsregarding classes, including inheritance, can be postponed to later in a course.

Although this book introduces classes early, it does not neglect traditional program-ming techniques, such as top-down design and loop design techniques. These older topicsmay no longer be glamorous, but they are information that all beginning students need.

Generic ProgrammingStudents are introduced to type parameters when they cover vectors in Chapter 10. Vectorsare presented in their latest version, when includes a type parameter for the base type ofthe vector. Students are then shown how to define their own classes that include a typeparameter.

Language Details and Sample CodeThe book teaches programming technique, rather than simply the Java language. However,neither students nor instructors would be satisfied with an introductory programmingcourse that did not also teach the programming language. Until you calm a student’s fearsabout language details, it is often impossible to focus her or his attention on bigger issues.For this reason, the book gives complete explanations of Java language features and lots ofsample code. Programs are presented in their entirety, along with sample input and output.In many cases, in addition to the complete examples in the text, extra complete examplesare available over the Internet.

Self-Test QuestionsSelf-test questions are spread throughout each chapter. These questions have a wide rangeof difficulty levels. Some require only a one-word answer, whereas others require thereader to write an entire, nontrivial program. Complete answers for all the self-test ques-tions, including those requiring full programs, are given at the end of each chapter.

Class TestedThe material in the book has been fully class tested. Much of the material and many of themethods of presentation were revised in response to this testing.

Support MaterialThe support materials described here can be obtained from the publisher or over theInternet.

x Preface for Instructors

Support ResourcesThe source code from the book, code for extra programming examples, and links todownload locations for Java compilers and programming environments are provided onthe book’s web site:

http://www.prenhall.com/savitch

Instructor’s Resource GuideInstructor tools include a chapter-by-chapter Instructor’s Resource Guide that containsnumerous teaching hints, quiz questions with solutions, solutions to many programmingexercises, PowerPoint slides, and other teaching resources. Instructors should contact theirPrentice Hall sales representative to receive information on how to access the Instructor’sweb site. For the name and number of your sales representative, contact Prentice Hall viathe following web site:

http://www.prenhall.com/

Walter [email protected]://www.cse.ucsd.edu/users/savitch

xi

PREFACE FOR STUDENTSThis book is designed to teach you the Java programming language and, even more impor-tantly, to teach you basic programming techniques. It requires no previous programmingexperience and no mathematics other than some simple high school algebra. However, toget the full benefit of the book, you should have a version of Java available on your com-puter, so that you can practice with the examples and techniques given. You should haveversion 5.0 (or higher) of Java. (Sun has changed the way it numbers version. Version 5.0was formerly called version 1.5 and you may still find it referred to as version 1.5 in somecontexts. If you have a copy of Java called “version 1.5,” that should be fine.)

If You Have Programmed BeforeYou need no previous programming experience to use this book. It was designed forbeginners. If you happen to have had experience with some other programming language,do not assume that Java is the same as the programming language(s) you are accustomedto using. All languages are different, and the differences, even if small, are large enough togive you problems. Read at least the boxed material in Section 1.3 of Chapter 1 and all ofthe boxed material in Chapters 2 and 3. By the time you reach Chapter 4, you would bewise to read the entire chapter.

If you have programmed before in either C or C++, the transition to Java can be trouble-some. At first glance, Java may seem almost the same as C or C++. However, Java is verydifferent from these languages, and you need to be aware of the differences. Appendix 11compares Java and C++ to help you see what the differences are.

Copies of the Programs in the TextAll the programs and other software examples in the book are available for downloadingfrom the book’s web site, so that you can practice with these examples without having totype them into your computer.

Obtaining a Copy of JavaThere are links on the book’s web site that lead you to sites for downloading Java com-pilers and programming environments. For beginners we recommend Sun’s Java SDKfor your Java compiler and related software and TextPad as a simple editor environmentfor writing Java code. When downloading the Java SDK, be sure to obtain a versionnumber of 5.0 or higher.

Books Web SiteThe source code from the book, code for extra programming examples, and links to down-load locations for Java compilers and programming environments are provided on thebook’s web site:

http://www.prenhall.com/savitch

xii Preface for Students

Self-Test QuestionsEach chapter contains numerous self-test questions. Complete answers to these questionsare given at the end of each chapter. One of the best ways to practice what you are learningis to do the self-test questions before you look at the answers.

This Text Is Also a Reference BookIn addition to using this book as a textbook, you can and should use it as a reference.When you need to check a point that you have forgotten or that you hear mentioned bysomebody, but have not yet learned yourself, just look in the index. Many index entriesgive a page number for “quick reference.” Turn to this quick reference page. It will con-tain a short entry, usually set off in a box, that gives all the essential points on that topic.You can do this to check details of the Java language as well as details on programmingtechniques.

Boxed sections in every chapter give you a quick summary of the main points in thatchapter. You can use these boxes to review the chapter, or to check details of the Java lan-guage.

We Want Your OpinionsThis book was written for you, and we would like to hear any comments you have on it.You can contact me via e-mail at the following address:

[email protected]

Unfortunately, I cannot provide you with answers to the programming exercises. Onlyinstructors who adopt the book can receive (selected) answers from the publisher. For helpwith the programming exercises, you will have to contact your instructor. (Even if you arenot enrolled in a class, I still cannot provide answers to programming exercises.) Butremember that there are answers to all the self-test questions at the end of each chapter.

Walter Savitchhttp://www.cse.ucsd.edu/users/savitch

xiii

ACKNOWLEDGMENTSI thank the Computer Science and Engineering Department of the University of Califor-nia, San Diego (UCSD), which is my home department and the place where I tested muchof this material. Many students in my classes were kind enough to help correct preliminaryversions of this text. These student comments and the comments of instructors who class-tested this book were a tremendous help in shaping the final book. In particular, I extend aspecial thanks to Carole McNamee of California State University, Sacramento, and to PaulKube of UCSD for their detailed feedback and class testing of earlier editions of the book.I also extend a special thanks to Robert Burton of BYU for preparing a detailed analysis ofa draft for this edition. Their comments have helped tremendously in shaping this book.

I thank all the reviewers who took the time to read drafts of earlier editions of the book.They provided invaluable detailed comments and suggestions that continue to benefit thisnew edition. In alphabetical order, they are

Jim Buffenbarger—Idaho State UniversityRobert P. Burton—Brigham Young University Steve Cater—Kettering University Martin Chelten—Moorpark Community CollegeMichael Clancy—University of California, BerkeleyTom Cortina—SUNY, Stony Brook Prasun Dewan—University of North CarolinaLaird Dornan—Sun Microsystems, Inc.H. E. Dunsmore—Purdue University, LafayetteAdel Elmaghraby—University of LouisvilleGobi Gopinath—Suffolk County Community College. Le Gruenwald—University of OklahomaGopal Gupta—University of Texas, Dallas Ricci Heishman—North Virginia Community College Robert Herrmann—Sun Microsystems, Inc., Java SoftRobert Holloway—University of Wisconsin, MadisonLily Hou—Carnegie Mellon UniversityRob Kelly—SUNY, Stony BrookMichele Kleckner—Elon College Mike Litman—Western Illinois University Blayne Mayfield—Oklahoma State UniversityJohn Motil—California State University, NorthridgeMichael Olan—Stockton StateJames Roberts—Carnegie Mellon UniversityAlan Saleski—Loyola University, ChicagoNan C. Schaller—Rochester Institute of TechnologyRyan Shoemaker—Sun Microsystems, Inc.Ken Slonneger—University of IowaDonald E. Smith—Rutgers UniversityBoyd Trolinger—Butte College Subramanian Vijayarangam—University of Massachusetts, Lowell

xiv Acknowledgments

I would to also thank the reviewers of this new edition:

Robert Burton--Brigham Young UniversityEd Gellenbeck--Central Washington UniversityAnthony Larrain--Depaul UniversityMichael Long--California State UniversityDrew McDermott--Yale UniversityKen Slonneger--University of IowaNavabi Tadayon--Arizona State UniversityRichard Whitehouse--Arizona State UniversityMichael Young--University of Oregon

I also thank all the individuals at Prentice Hall who organized the reviewing and pro-duction of this book. In particular, I thank Toni Holm, Patrick Lindner, and Irwin Zucker.I extend a special thanks to my publisher, Alan Apt, for his invaluable support and advicethroughout the writing and production process. All these wonderful people cheerfully dida great job.

Lew Rakocy prepared the programming solutions for the instructor’s guide, RobertBurton prepared the PowerPoint slides. I thank both of them for their conscientious work.

I thank Sun Microsystems for allowing me to use the Duke icon in a number of my GUIexamples.

W.S.

xv

DEPENDENCY CHARTThis chart shows the prerequisites for the chapters in the book. If there is a line betweentwo boxes, the material in the higher box should be covered before the material in thelower box. Minor variations to this chart are discussed in the “Prerequisites” section at thestart of each chapter. These variations usually provide more, rather than less, flexibilitythan what is shown on the chart.

.

Section 11.1 Basic Recursion

Chapter 1Introduction

Chapter 2Primitive Types, Strings

Chapter 3Flow of Control Section 6.1

Array BasicsChapters 4 and 5

Basic Classes and Methods

Chapter 11*Recursion

Section 10.1‡Vectors

Chapter 7Inheritance

Chapter 6Arrays

Sections 9.1 and 9.2Text Files

Section 8.1Exception Basics

Chapter 8*Exceptions

Chapter 13Applets

Chapter 14More Swing

Chapter 12**Basic Swing

Section 10.2** Linked Lists

Section 9.4 Binary Files

Section 9.3 The File Class

* Note that some sections of these chapters can be covered sooner. Those sections are given in this chart.** See the chapter’s “Prerequisites” section for full details.‡ Most of Section 10.1 (“Vectors”) can be covered before covering inheritance.

Section 10.3Generics

xvii

BRIEF TABLE OF CONTENTSChapter 1 Introduction to Computers and Java 3Chapter 2 Primitive Types, Strings, and Console I/O 45Chapter 3 Flow of Control 129Chapter 4 Defining Classes and Methods 221Chapter 5 More About Objects and Methods 315Chapter 6 Arrays 417Chapter 7 Inheritance 501Chapter 8 Exception Handling 569Chapter 9 Streams and File I/O 641Chapter 10 Dynamic Data Structures and Generics 717Chapter 11 Recursion 787Chapter 12 Window Interfaces Using Swing 827Chapter 13 Applets and HTML 913Chapter 14 More Swing 941Appendix 1 Keywords 1010Appendix 2 Precedence Rules 1011Appendix 3 Unicode Character Set 1012Appendix 4 SavitchIn 1013Appendix 5 Protected and Package Modifiers 1026Appendix 6 The DecimalFormat Class 1027Appendix 7 The Iterator Interface 1030Appendix 8 Cloning 1031Appendix 9 Javadoc 1034Appendix 10 The JOptionPane Class 1036Appendix 11 Differences between C++ and Java 1042

Index 1045

xviii

TABLE OF CONTENTSCHAPTER 1 Introduction to Computers and Java 3

Objectives 4Prerequisites 41.1 Computer Basics 5Hardware and Memory 5Programs 7Programming Languages and Compilers 9Java Byte-Code 10Class Loader 12

1.2 Designing Programs 13Object-Oriented Programming 13Encapsulation 14Polymorphism 15Inheritance 16If You Know Some Other Programming Language 17Algorithms 17Reusable Components 18Testing and Debugging 19

1.3 A Sip of Java 21History of the Java Language 21Applets 22A First Java Application Program 22Compiling a Java Program or Class 27Running a Java Program 29

1.4 Graphics Supplement (Optional) 29Objects and Methods 30A Sample Graphics Applet 30Size and Positions of Figures 33Drawing Arcs 36Running an Applet 36Chapter Summary 39Answers to Self-Test Questions 40Programming Projects 42

CHAPTER 2 Primitive Types, Strings, and Console I/O 45Objectives 46Prerequisites 462.1 Primitive Types and Expressions 47Variables 47Java Identifiers 51Primitive Types 52Assignment Statements 53Specialized Assignment Operators 55Simple Screen Output 56Simple Input 56

Table of Contents xix

Number Constants 58Assignment Compatibilities 59Type Casting 61Programming Tip: Initialize Variables 63Arithmetic Operators 66Parentheses and Precedence Rules 67Case Study: Vending Machine Change 69Increment and Decrement Operators 74More about the Increment and Decrement Operators 75

2.2 The Class String 76String Constants and Variables 76Concatenation of Strings 77Classes 78String Methods 79String Processing 83Escape Characters 84The Unicode Character Set 85

2.3 Keyboard and Screen I/O 87Screen Output 87Keyboard Input 90

2.4 Documentation and Style 98Programming Tip: Use Meaningful Names for Variables 99Documentation and Comments 99Indenting 102Named Constants 102

2.5 Graphics Supplement (Optional) 106Programming Example: Style Rules Applied to a Graphics Applet 106JOptionPane 106Inputting Other Numeric Types 115Programming Example: Change-Making Program with Windowing I/O 117Chapter Summary 120Answers to Self-Test Questions 120Programming Projects 125

CHAPTER 3 Flow of Control 129Objectives 130Prerequisites 130

3.1 Branching Statements 130The if-else Statement 130Introduction to Boolean Expressions 134Programming Tip: Alphabetical Order 139Nested Statements and Compound Statements 142Multibranch if-else Statements 145

xx Table of Contents

Programming Example: Assigning Letter Grades 146The switch Statement 149The Conditional Operator (Optional) 153

3.2 Java Loop Statements 155while Statements 156The do-while Statement 160Programming Example: Bug Infestation 164The for Statement 168The Comma in for Statements (Optional) 172The break Statement in Loops 175The exit Method 177

3.3 Programming with Loops 179The Loop Body 179Initializing Statements 181Ending a Loop 182Programming Example: Nested Loops 183Programming Tip: Avoid Declaring Variables in a Loop Body 184Loop Bugs 184Tracing Variables 188

3.4 The Type boolean 189Boolean Expressions and Boolean Variables 190Programming Tip: Naming Boolean Variables 191Precedence Rules 192Input and Output of Boolean Values 195Case Study: Using a Boolean Variable to End a Loop 195

3.5 Graphics Supplement (Optional) 199Specifying a Drawing Color 199Programming Example: A Multiface Applet 203The drawString Method 208A JOptionPane Yes/No Window 209Chapter Summary 211Answers to Self-Test Questions 211Programming Projects 217

CHAPTER 4 Defining Classes and Methods 221Objectives 222Prerequisites 222

4.1 Class and Method Definitions 222Class Files and Separate Compilation 224Instance Variables 225Using Methods 228void Method Definitions 231Methods That Return a Value 233The this Parameter 238Local Variables 240

Table of Contents xxi

Blocks 242Parameters of a Primitive Type 243Summary of Class and Method Definition Syntax 249

4.2 Information Hiding and Encapsulation 250Information Hiding 250Programming Tip: Parameter Names Are Local to the Method 251Precondition and Postcondition Comments 251The public and private Modifiers 254Programming Tip: Instance Variables Should Be private 257Programming Example: A Purchase Class 261Encapsulation 265Automatic Documentation with javadoc 268UML Class Diagrams 268

4.3 Objects and Reference 270Variables of a Class Type and Objects 270Programming Example: A Species Class 279Boolean-Valued Methods 282Class Parameters 284Comparing Class Parameters and Primitive-Type Parameters 287

4.4 Graphics Supplement (Optional) 291The Graphics Class 291Programming Example: Multiple Faces Redone with

a Helping Method 294The init Method 298Adding Labels to an Applet 298Chapter Summary 302Answers to Self-Test Questions 303Programming Projects 310

CHAPTER 5 More About Objects and Methods 315Objectives 316Prerequisites 316

5.1 Programming with Methods 317Methods Calling Methods 317Programming Tip: Make Helping Methods Private 323

5.2 Static Methods and Static Variables 326Static Methods 326Static Variables (Optional) 332The Math Class 334Integer, Double, and Other Wrapper Classes 337

5.3 Designing Methods 343Case Study: Formatting Output 343Top-Down Design 348Testing Methods 350

xxii Table of Contents

5.4 Overloading 352Overloading Basics 352Programming Example: A Pet Class 355Programming Example: A Class for Money 363

5.5 Constructors 369Defining Constructors 370Programming Tip: You Can Use Other Methods in a Constructor 378

5.6 Information Hiding Revisited 380

5.7 Packages 384Packages and Importing 384Package Names and Directories 385Name Clashes 388

5.8 Graphics Supplement (Optional) 389Programming Tip: Code Appearance and Actions Separately 389Adding Buttons 390Event-Driven Programming 391Programming Example: A Complete Button Applet 391Programming Buttons 392Icons 399Changing Visibility 401Programming Example: An Example of Changing

Visibility 401What’s Next 405Chapter Summary 405Answers to Self-Test Questions 406Programming Projects 412

CHAPTER 6 Arrays 417Objectives 418Prerequisites 418

6.1 Array Basics 419Creating and Accessing Arrays 419Array Details 420Programming Tip: Use Singular Array Names 424The length Instance Variable 425Programming Tip: Use a for Loop to Step Through an Array 427Initializing Arrays 429

6.2 Arrays in Classes and Methods 430Case Study: Sales Report 430Indexed Variables as Method Arguments 438Entire Arrays as Method Arguments 440Arguments for the Method main 441Methods That Return Arrays 446

Table of Contents xxiii

6.3 Programming with Arrays and Classes 449Programming Example: A Specialized List Class 450Partially Filled Arrays 457Searching an Array 457

6.4 Sorting Arrays 460Selection Sort 460Other Sorting Algorithms 465

6.5 Multidimensional Arrays 465Multidimensional-Array Basics 467Multidimensional-Array Parameters and Returned Values 470Implementation of Multidimensional Arrays 471Ragged Arrays (Optional) 475Programming Example: Employee Time Records 476

6.6 Graphics Supplement (Optional) 482Graphics Supplement Part 1: Text Areas and Text Fields 483Programming Example: A Question-and-Answer Applet 483JTextArea and JTextField Objects 483Graphics Supplement Part 2: Drawing Polygons 487Drawing Polygons 487Chapter Summary 491Answers to Self-Test Questions 492Programming Projects 497

CHAPTER 7 Inheritance 501Objectives 502Prerequisites 502

7.1 Inheritance Basics 502Programming Example: A Person Class 503Derived Classes 504Overriding Method Definitions 507Overriding Versus Overloading 508The final Modifier 508Programming Tip: Assume That Your Coworkers Are Malicious 510UML Inheritance Diagrams 510

7.2 Programming with Inheritance 513Constructors in Derived Classes 513The this Method (Optional) 514Call to an Overridden Method 515Programming Example: Multilevel Derived Classes 516A Subtle Point About Overloading and Overriding (Optional) 521Programming Tip: An Object Can Have More than One Type 522Programming Tip: “Is a” and “Has a” Relations 525The Class Object 526Case Study: Character Graphics 528

xxiv Table of Contents

Abstract Classes 538Interfaces 542

7.3 Dynamic Binding and Polymorphism 544Dynamic Binding 544Type Checking and Dynamic Binding 546Dynamic Binding with toString 547Polymorphism 548

7.4 Graphics Supplement (Optional) 551The Class JApplet 551The Class JFrame 552Window Events and Window Listeners 555The ActionListener Interface 556Programming Example: Happy Face as a JFrame 557What To Do Next 558Chapter Summary 559Answers to Self-Test Questions 559Programming Projects 565

CHAPTER 8 Exception Handling 569Objectives 570Prerequisites 570

8.1 Basic Exception Handling 571Exceptions in Java 571Predefined Exception Classes 583ArrayIndexOutOfBoundsException (Alternative Ordering) 584

8.2 Defining Exception Classes 585Defining Your Own Exception Classes 585Programming Tip: When to Define an Exception Class 591

8.3 Using Exception Classes 596Declaring Exceptions (Passing the Buck) 596Exceptions That Do Not Need To Be Caught 600The AssertionError Class (Optional) 601Multiple Throws and Catches 601Programming Tip: Exception Handling and Information Hiding 605Programming Tip: When to Throw an Exception 607The finally Block (Optional) 609Rethrowing an Exception (Optional) 610Case Study: A Line-Oriented Calculator 611

8.4 Graphics Supplement (Optional) 625Exceptions in GUIs 625Programming Example: A JFrame Using Exceptions 626Chapter Summary 630Answers to Self-Test Questions 630Programming Projects 635

Table of Contents xxv

CHAPTER 9 Streams and File I/O 641Objectives 642Prerequisites 642

9.1 An Overview of Streams and File I/O 643The Concept of a Stream 643Why Use Files for I/O? 643Differences between Text Files and Binary Files 643

9.2 Text-File I/O 645Text-File Output with PrintWriter 645Text-File Input with BufferedReader 656Programming Example: Reading a File Name from the Keyboard 660The StringTokenizer Class 663The Classes FileReader and FileOutputStream 667

9.3 The File Class 669Using the File Class 669

9.4 Basic Binary-File I/O 672Output to Binary Files, Using ObjectOutputStream 673Some Details about writeUTF (Optional) 678Reading Input from a Binary File, Using ObjectInputStream 679The EOFException Class 685The Classes FileInputStream and FileOutputStream 688Programming Example: Processing a File of Binary Data 689

9.5 Object I/O with Object Streams 693Binary I/O of Class Objects 693The Serializable Interface 698Array Objects in Binary Files 699

9.6 Graphics Supplement (Optional) 701Programming Example: A JFrame GUI for Manipulating Files 701Chapter Summary 707Answers to Self-Test Questions 707Programming Projects 713

CHAPTER 10 Dynamic Data Structures and Generics 717Objectives 718Prerequisites 718

10.1 Vectors 719Using Vectors 719Programming Tip: Adding to a Vector 726Parameterized Classes and Generics 732

10.2 Linked Data Structures 733Linked Lists 733Inner Classes 744

xxvi Table of Contents

Node Inner Classes 745Iterators 746Programming Tip: Internal and External Iterators 759Exception Handling with Linked Lists 759Variations on a Linked List 763Other Linked Data Structures 765

10.3 Generics 765Generic Basics 766Programming Example: A Generic Linked List 768Chapter Summary 774Answers to Self-Test Questions 774Programming Projects 783

CHAPTER 11 Recursion 787Objectives 788Prerequisites 788

11.1 The Basics of Recursion 788Case Study: Digits to Words 789How Recursion Works 794Recursive versus Iterative Definitions 801Recursive Methods That Return a Value 801

11.2 Programming with Recursion 806Programming Tip: Ask Until the User Gets It Right 806Case Study: Binary Search 808Programming Tip: Generalize the Problem 812Programming Example: Merge Sort—A Recursive Sorting Method 816Chapter Summary 821Answers to Self-Test Questions 821Programming Projects 823

CHAPTER 12 Window Interfaces Using Swing 827Objectives 828Prerequisites 828

12.1 Background 829GUIs—Graphical User Interfaces 829Event-Driven Programming 829

12.2 Basic Swing Details 831Programming Example: A Simple Window 832More about Window Listeners 838Size Units for Screen Objects 840More on setVisible 841Programming Example: A Better Version of Our First Swing Program 843Programming Example: A Window with Color 846

Table of Contents xxvii

Some Methods of the Class JFrame 850Layout Managers 853

12.3 Buttons and Action Listeners 860Programming Example: Adding Buttons 860Buttons 862Action Listeners and Action Events 864Interfaces 869The Model–View–Controller Pattern 871

12.4 Container Classes 874The JPanel Class 874

12.5 The Container Class 877

12.6 Text I/O for GUIs 882Text Areas and Text Fields 882Programming Example: Labeling a Text Field 888Inputting and Outputting Numbers 890Programming Example: A GUI Adding Machine 893Catching a NumberFormatException 897Chapter Summary 900Answers to Self-Test Questions 901Programming Projects 909

CHAPTER 13 Applets and HTML 913Objectives 914Prerequisites 914

13.1 Applets 915Applet Basics 915Running an Applet 918Programming Example: An Adder Applet 918Adding Icons to an Applet 921

13.2 Introduction to HTML 924HTML Basics 924Programming Tip: A Simple HTML-Document Outline 926Inserting Hyperlinks 926Displaying a Picture 931Programming Tip: HTML Is a Low-Level Language 932

13.3 Applets in HTML 932Placing an Applet in an HTML Document 932The Older Applet Class (Optional) 935Applets and Security 936Chapter Summary 937Answers to Self-Test Questions 937Programming Projects 938

xxviii Table of Contents

CHAPTER 14 More Swing 941Objectives 942Prerequisites 942

14.1 Menus 942Programming Example: A GUI with a Menu 943Menu Bars, Menus, and Menu Items 943Nested Menus 948

14.2 Making GUIs Pretty (and More Functional) 950Adding Icons 950The JScrollPane Class for Scroll Bars 957Adding Borders 963

14.3 More Layout Managers 969The BoxLayout Manager Class 969Struts and Glue 973Setting the Spacing between Components 975The Box Container Class 975The CardLayout Manager 978

14.4 Inner Classes 984Helping Classes 984

14.5 More on Events and Listeners 986The WindowListener Interface 986Programming Example: Components with Changing Visibility 997Some More Details on Updating a GUI 1000

14.6 Another Look at the Swing Class Hierarchy 1001Buttons, Menus, and Abstract Buttons 1001Chapter Summary 1004Answers to Self-Test Questions 1004Programming Projects 1008

Appendix 12 Keywords 1010

Appendix 13 Precedence Rules 1011

Appendix 14 Unicode Character Set 1012

Appendix 15 SavitchIn 1013

Appendix 16 Protected and Package Modifiers 1026

Appendix 17 The DecimalFormat Class 1027Percent Notation 1027Scientific Notation (E-Notation) 1029

Appendix 18 The Iterator Interface 1030

Appendix 19 Cloning 1031

Appendix 20 Javadoc 1034

Table of Contents xxix

Commenting Classes for Use with javadoc 1034Running javadoc 1035

Appendix 21 The JOptionPane Class 1036A Sample Program Using JOptionPane 1036Multiline Output Windows 1041

Appendix 22 Differences between C++ and Java 1042Primitive Types 1042Strings 1042Flow of Control 1042Testing for Equality 1043main Method (Function) and Other Methods 1043Files and Including Files 1043Class and Method (Function) Definitions 1043No Pointers in Java 1043Method (Function) Parameters 1044Arrays 1044Garbage Collection 1044Other Comparisons 1044

Index 1045

Table of Contents xxx