Nov 12, 2004 ... without permission in writing from the publisher. For the exclusive use of adopters
of the book JAVA: An Introduction to Problem Solving and.
JAVA
™
An Introduction to Problem Solving & Programming Fourth Edition
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Thank you for purchasing a new copy of the best-selling Savitch Java book. The rave reviews 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 environment called CodeKey. It is an on-line, interactive tutorial for readers learning how to program with the Java programming language. You will be able to complete selected programming 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 existing programs from the book. Code Key will allow you to “test” your programs before submitting 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 necessary. You will be alerted to errors, and will be given programming hints on how to fix them. You can access CodeKey at www.prenhall.com/codekey
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
JAVA
™
An Introduction to Problem Solving & Programming Fourth Edition
WALTER SAVITCH
Upper Saddle River, NJ 07458 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
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 2005 005.13'3--dc22 2004057347 Vice President and Editorial Director, ECS: Marcia Horton Publisher: Alan R. Apt Associate Editor: Toni D. Holm Vice President and Director of Production and Manufacturing, ESM: David W. Riccardi Executive Managing Editor: Vince O’Brien Assistant Managing Editor: Camille Trentacoste Production Editor: Irwin Zucker Director of Creative Services: Paul Belfanti Art Director: Kenny Beck Cover Designer: Laura Gardner Art Editor: Xiaohong Zhu Manufacturing Manager: Trudy Pisciotti Manufacturing Buyer: Lisa McDowell Marketing Manager: Pamela Hersperger Marketing Assistant: Barrie Reinhold ©1999, 2001, 2004, 2005 by Pearson Education Inc. Pearson Prentice Hall Upper 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 America 10 9 8 7 6 5 4 3 2 1 ISBN 0-13-149202-0 Pearson Education Ltd., London Pearson Education Australia Pty. Ltd., Sydney Pearson Education Singapore, Pte. Ltd. Pearson Education North Asia Ltd., Hong Kong Pearson Education Canada, Inc., Toronto Pearson Educación de Mexico, S.A. de C.V. Pearson Education—Japan, Tokyo Pearson Education Malaysia, Pte. Ltd. Pearson Education, Inc., Upper Saddle River, New Jersey
TRADEMARK INFORMATION ANSI 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) PRELIMINARY PROOFS DreamWeaver (Maacromedia, Inc.) © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GoLive (Adobe Inc.) This material is protected under all copyright laws as they currently exist. No portion of thisSystems material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
To Christina
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Savitch4e_FeaturesppFMv2.qxp 11/12/04 8:10 PM Page 2
4.4 GRAPHICS SUPPLEMENT (OPTIONAL)
▲
FEATURES OF THIS TEXT Early optional graphics supplements cover GUIs built using both applets and the JFrame class are integrated throughout the text. Advanced GUI chapters give additional graphics material.
The whole is more than the sum of its parts. —Proverb
Now that we have explained methods and parameters more completely, we will revisit material 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, we will explain the Graphics class more completely, and we will introduce some additional drawing methods. Finally, we introduce the method init, which is another applet method similar to paint but used for different purposes.
▲
FAQ
Graphics Supplement (Optional)
▲
Provides students answers to frequently asked questions within the context of the chapter.
▲
Quick Reference
Gotcha
Helps students identify possible programming pitfalls.
▲
Provides concise, user-friendly reference for key programming concepts.
Java Tip
Gives students helpful information about the Java programming language.
▲
Remember
▲
Reinforces concepts presented in the chapter.
Self-Test Questions
Provides students the opportunity to practice skills learned in the chapter.
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
PREFACE FOR INSTRUCTORS This book is designed for a first course in programming and computer science. It covers programming techniques, as well as the basics of the Java programming language. It is suitable for courses as short as one quarter or as long as a full academic year. No previous programming experience is required, nor is any mathematics, other than a little high school algebra. The book can also be used for a course designed to teach Java to students who have already had another programming course, in which case the first few chapters can be assigned as outside reading. This book uses only standard classes available as part of Java. No additional classes are needed. All of the code in this book has been tested using Sun’s Java JDK version 5.0, beta 2 release. To be fully compatible with this book, the Java used in your class should be version 5.0 or higher.1
Changes in This Edition If you have not used the third edition of this text, you can skip this subsection. If you have used the third edition, this subsection will tell you how this fourth edition differs from the third. For instructors, the transition from the third to this fourth edition is easy. You can teach the same course, presenting basically the same topics in the same order with only very minor changes in the material covered. The largest required change is that this edition uses the new Scanner class available in Java version 5.0 in place of the class SavichIn.2 If you wish to change your course further, this edition includes Graphics Supplement sections that allow you to (optionally) add early graphics coverage. This edition also adds coverage of generic programming with type parameters. Chapter 1 through 9 each end with a Graphics Supplement section that covers graphics applications and GUIs using applets as well as JFrames. These Graphics Supplement sections 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 the detailed coverage of Swing. The other major changes to this edition have to do with updating the text to match Java version 5.0: The new Scanner class is used for keyboard input. We explain and use automatic boxing and unboxing. The coverage of vectors has been updated to use generic type parameters. An introduction to type parameters and generics is given in Chapter 10.
Latest Java Coverage This 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 and you 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 is available over the Web. However, SavitchIn is not used anywhere in the text.
vii PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
viii
Preface for Instructors unboxing, we do vectors using type parameters, and we include an introduction to generic programming using type parameters. As we wrote this book, we checked all code using Sun’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 you adapt to the book. This book does not tightly prescribe the sequence in which your course must cover topics. You can easily change the order in which you cover chapters and sections. The particulars about rearranging material are explained in the dependency chart that follows this preface and in more detail in the “Prerequisites” section at the start of each chapter. This book uses no specialized libraries. Only standard classes available as part of the standard Java libraries are used.
Early Graphics Optional Graphic Supplement sections end chapters starting with Chapter 1. This allows you 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 the JFrame class. Any time after Chapter 7, you may move on to the main chapters on GUI programming (Chapters 12–14). Alternatively, the Graphics Supplement sections continue through Chapter 9, allowing you to continue with a mix of graphics and more traditional programming. Instructors who prefer to postpone the coverage of graphics may postpone or skip the Graphics Supplement sections.
Coverage of Problem-Solving and Programming Techniques This book is designed to teach students basic problem-solving and programming techniques and is not simply a book about Java syntax. It contains numerous case studies and programming tips, as well as many sections that explain important problem-solving and programming techniques, such as loop design techniques, debugging techniques, style techniques, abstract data types, and basic object-oriented programming techniques, including UML and event-driven programming, and generic programming using type parameters.
Object-Oriented and Traditional Techniques Any course that really teaches Java must teach classes early, since everything in Java involves classes. A Java program is a class. The data type for strings of characters is a class. Even the behavior of the equals operator (==) depends on whether it is comparing objects from classes or simpler data items. Classes cannot be avoided, except by means of absurdly long and complicated “magic formulas.” This book introduces classes fairly early. Some exposure to using classes is given in Chapters 1 and 2. Chapter 4 covers how PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Preface for Instructors ix to define classes. All of the basic information about classes, including inheritance, is presented by the end of Chapter 7 (even if you omit Chapter 6). However, some topics regarding classes, including inheritance, can be postponed to later in a course. Although this book introduces classes early, it does not neglect traditional programming techniques, such as top-down design and loop design techniques. These older topics may no longer be glamorous, but they are information that all beginning students need.
Generic Programming Students are introduced to type parameters when they cover vectors in Chapter 10. Vectors are presented in their latest version, when includes a type parameter for the base type of the vector. Students are then shown how to define their own classes that include a type parameter.
Language Details and Sample Code The book teaches programming technique, rather than simply the Java language. However, neither students nor instructors would be satisfied with an introductory programming course that did not also teach the programming language. Until you calm a student’s fears about 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 of sample 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 examples are available over the Internet.
Self-Test Questions Self-test questions are spread throughout each chapter. These questions have a wide range of difficulty levels. Some require only a one-word answer, whereas others require the reader to write an entire, nontrivial program. Complete answers for all the self-test questions, including those requiring full programs, are given at the end of each chapter.
Class Tested The material in the book has been fully class tested. Much of the material and many of the methods of presentation were revised in response to this testing.
Support Material The support materials described here can be obtained from the publisher or over the Internet.
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
x Preface for Instructors
Support Resources The source code from the book, code for extra programming examples, and links to download locations for Java compilers and programming environments are provided on the book’s web site: http://www.prenhall.com/savitch
Instructor’s Resource Guide Instructor tools include a chapter-by-chapter Instructor’s Resource Guide that contains numerous teaching hints, quiz questions with solutions, solutions to many programming exercises, PowerPoint slides, and other teaching resources. Instructors should contact their Prentice Hall sales representative to receive information on how to access the Instructor’s web site. For the name and number of your sales representative, contact Prentice Hall via the following web site: http://www.prenhall.com/
Walter Savitch
[email protected] http://www.cse.ucsd.edu/users/savitch
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
PREFACE FOR STUDENTS This book is designed to teach you the Java programming language and, even more importantly, to teach you basic programming techniques. It requires no previous programming experience and no mathematics other than some simple high school algebra. However, to get the full benefit of the book, you should have a version of Java available on your computer, so that you can practice with the examples and techniques given. You should have version 5.0 (or higher) of Java. (Sun has changed the way it numbers version. Version 5.0 was formerly called version 1.5 and you may still find it referred to as version 1.5 in some contexts. If you have a copy of Java called “version 1.5,” that should be fine.)
If You Have Programmed Before You need no previous programming experience to use this book. It was designed for beginners. 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 accustomed to using. All languages are different, and the differences, even if small, are large enough to give you problems. Read at least the boxed material in Section 1.3 of Chapter 1 and all of the boxed material in Chapters 2 and 3. By the time you reach Chapter 4, you would be wise to read the entire chapter. If you have programmed before in either C or C++, the transition to Java can be troublesome. At first glance, Java may seem almost the same as C or C++. However, Java is very different from these languages, and you need to be aware of the differences. Appendix 11 compares Java and C++ to help you see what the differences are.
Copies of the Programs in the Text All the programs and other software examples in the book are available for downloading from the book’s web site, so that you can practice with these examples without having to type them into your computer.
Obtaining a Copy of Java There are links on the book’s web site that lead you to sites for downloading Java compilers and programming environments. For beginners we recommend Sun’s Java SDK for your Java compiler and related software and TextPad as a simple editor environment for writing Java code. When downloading the Java SDK, be sure to obtain a version number of 5.0 or higher.
Books Web Site The source code from the book, code for extra programming examples, and links to download locations for Java compilers and programming environments are provided on the book’s web site: http://www.prenhall.com/savitch
xi PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xii
Preface for Students
Self-Test Questions Each chapter contains numerous self-test questions. Complete answers to these questions are given at the end of each chapter. One of the best ways to practice what you are learning is to do the self-test questions before you look at the answers.
This Text Is Also a Reference Book In 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 by somebody, but have not yet learned yourself, just look in the index. Many index entries give a page number for “quick reference.” Turn to this quick reference page. It will contain 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 programming techniques. Boxed sections in every chapter give you a quick summary of the main points in that chapter. You can use these boxes to review the chapter, or to check details of the Java language.
We Want Your Opinions This 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. Only instructors who adopt the book can receive (selected) answers from the publisher. For help with the programming exercises, you will have to contact your instructor. (Even if you are not enrolled in a class, I still cannot provide answers to programming exercises.) But remember that there are answers to all the self-test questions at the end of each chapter. Walter Savitch
http://www.cse.ucsd.edu/users/savitch
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
ACKNOWLEDGMENTS I thank the Computer Science and Engineering Department of the University of California, San Diego (UCSD), which is my home department and the place where I tested much of this material. Many students in my classes were kind enough to help correct preliminary versions of this text. These student comments and the comments of instructors who classtested this book were a tremendous help in shaping the final book. In particular, I extend a special thanks to Carole McNamee of California State University, Sacramento, and to Paul Kube 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 of a 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 this new edition. In alphabetical order, they are Jim Buffenbarger—Idaho State University Robert P. Burton—Brigham Young University Steve Cater—Kettering University Martin Chelten—Moorpark Community College Michael Clancy—University of California, Berkeley Tom Cortina—SUNY, Stony Brook Prasun Dewan—University of North Carolina Laird Dornan—Sun Microsystems, Inc. H. E. Dunsmore—Purdue University, Lafayette Adel Elmaghraby—University of Louisville Gobi Gopinath—Suffolk County Community College. Le Gruenwald—University of Oklahoma Gopal Gupta—University of Texas, Dallas Ricci Heishman—North Virginia Community College Robert Herrmann—Sun Microsystems, Inc., Java Soft Robert Holloway—University of Wisconsin, Madison Lily Hou—Carnegie Mellon University Rob Kelly—SUNY, Stony Brook Michele Kleckner—Elon College Mike Litman—Western Illinois University Blayne Mayfield—Oklahoma State University John Motil—California State University, Northridge Michael Olan—Stockton State James Roberts—Carnegie Mellon University Alan Saleski—Loyola University, Chicago Nan C. Schaller—Rochester Institute of Technology Ryan Shoemaker—Sun Microsystems, Inc. Ken Slonneger—University of Iowa Donald E. Smith—Rutgers University Boyd Trolinger—Butte College Subramanian Vijayarangam—University of Massachusetts, Lowell
xiii PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xiv Acknowledgments I would to also thank the reviewers of this new edition: Robert Burton--Brigham Young University Ed Gellenbeck--Central Washington University Anthony Larrain--Depaul University Michael Long--California State University Drew McDermott--Yale University Ken Slonneger--University of Iowa Navabi Tadayon--Arizona State University Richard Whitehouse--Arizona State University Michael Young--University of Oregon I also thank all the individuals at Prentice Hall who organized the reviewing and production 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 advice throughout the writing and production process. All these wonderful people cheerfully did a great job. Lew Rakocy prepared the programming solutions for the instructor’s guide, Robert Burton 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 GUI examples. W.S.
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
DEPENDENCY CHART This chart shows the prerequisites for the chapters in the book. If there is a line between two boxes, the material in the higher box should be covered before the material in the lower box. Minor variations to this chart are discussed in the “Prerequisites” section at the start of each chapter. These variations usually provide more, rather than less, flexibility than what is shown on the chart. .
Chapter 1 Introduction Chapter 2 Primitive Types, Strings Chapter 3 Flow of Control
Section 6.1 Array Basics
Chapter 7 Inheritance
Chapters 4 and 5 Basic Classes and Methods Section 8.1 Exception Basics
Section 10.1‡ Vectors Chapter 12** Basic Swing
Chapter 13 Applets
Chapter 8* Exceptions
Chapter 14 More Swing
Chapter 6 Arrays
Section 10.2** Linked Lists
Section 11.1 Basic Recursion Sections 9.1 and 9.2 Text Files
Chapter 11* Recursion
Section 10.3 Generics 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.
xv PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
BRIEF TABLE OF CONTENTS Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix 1 Appendix 2 Appendix 3 Appendix 4 Appendix 5 Appendix 6 Appendix 7 Appendix 8 Appendix 9 Appendix 10 Appendix 11
Introduction to Computers and Java 3 Primitive Types, Strings, and Console I/O 45 Flow of Control 129 Defining Classes and Methods 221 More About Objects and Methods 315 Arrays 417 Inheritance 501 Exception Handling 569 Streams and File I/O 641 Dynamic Data Structures and Generics 717 Recursion 787 Window Interfaces Using Swing 827 Applets and HTML 913 More Swing 941 Keywords 1010 Precedence Rules 1011 Unicode Character Set 1012 SavitchIn 1013 Protected and Package Modifiers 1026 The DecimalFormat Class 1027 The Iterator Interface 1030 Cloning 1031 Javadoc 1034 The JOptionPane Class 1036 Differences between C++ and Java 1042 Index 1045
xvii PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
TABLE OF CONTENTS CHAPTER 1
Introduction to Computers and Java 3
Objectives 4 Prerequisites 4
1.1 Computer Basics 5 Hardware and Memory 5 Programs 7 Programming Languages and Compilers 9 Java Byte-Code 10 Class Loader 12 1.2 Designing Programs 13 Object-Oriented Programming 13 Encapsulation 14 Polymorphism 15 Inheritance 16 If You Know Some Other Programming Language 17 Algorithms 17 Reusable Components 18 Testing and Debugging 19 1.3 A Sip of Java 21 History of the Java Language 21 Applets 22 A First Java Application Program 22 Compiling a Java Program or Class 27 Running a Java Program 29 1.4 Graphics Supplement (Optional) 29 Objects and Methods 30 A Sample Graphics Applet 30 Size and Positions of Figures 33 Drawing Arcs 36 Running an Applet 36 Chapter Summary 39 Answers to Self-Test Questions 40 Programming Projects 42
CHAPTER 2
Primitive Types, Strings, and Console I/O 45
Objectives 46 Prerequisites 46
2.1 Primitive Types and Expressions 47 Variables 47 Java Identifiers 51 Primitive Types 52 Assignment Statements 53 Specialized Assignment Operators 55 Simple Screen Output 56 Simple Input 56
PRELIMINARYxviii PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents xix Number Constants 58 Assignment Compatibilities 59 Type Casting 61 Programming Tip: Initialize Variables 63 Arithmetic Operators 66 Parentheses and Precedence Rules 67 Case Study: Vending Machine Change 69 Increment and Decrement Operators 74 More about the Increment and Decrement Operators 75 2.2 The Class String 76 String Constants and Variables 76 Concatenation of Strings 77 Classes 78 String Methods 79 String Processing 83 Escape Characters 84 The Unicode Character Set 85 2.3 Keyboard and Screen I/O 87 Screen Output 87 Keyboard Input 90 2.4 Documentation and Style 98 Programming Tip: Use Meaningful Names for Variables 99 Documentation and Comments 99 Indenting 102 Named Constants 102 2.5 Graphics Supplement (Optional) 106 Programming Example: Style Rules Applied to a Graphics Applet 106 JOptionPane 106 Inputting Other Numeric Types 115 Programming Example: Change-Making Program with Windowing I/O 117 Chapter Summary 120 Answers to Self-Test Questions 120 Programming Projects 125
CHAPTER 3
Flow of Control 129
Objectives 130 Prerequisites 130
3.1 Branching Statements 130 The if-else Statement 130 Introduction to Boolean Expressions 134 Programming Tip: Alphabetical Order 139 Nested Statements and Compound Statements 142 Multibranch if-else Statements 145 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xx
Table of Contents Programming Example: Assigning Letter Grades 146 The switch Statement 149 The Conditional Operator (Optional) 153 3.2 Java Loop Statements 155 while Statements 156 The do-while Statement 160 Programming Example: Bug Infestation 164 The for Statement 168 The Comma in for Statements (Optional) 172 The break Statement in Loops 175 The exit Method 177 3.3 Programming with Loops 179 The Loop Body 179 Initializing Statements 181 Ending a Loop 182 Programming Example: Nested Loops 183 Programming Tip: Avoid Declaring Variables in a Loop Body 184 Loop Bugs 184 Tracing Variables 188 3.4 The Type boolean 189 Boolean Expressions and Boolean Variables 190 Programming Tip: Naming Boolean Variables 191 Precedence Rules 192 Input and Output of Boolean Values 195 Case Study: Using a Boolean Variable to End a Loop 195 3.5 Graphics Supplement (Optional) 199 Specifying a Drawing Color 199 Programming Example: A Multiface Applet 203 The drawString Method 208 A JOptionPane Yes/No Window 209 Chapter Summary 211 Answers to Self-Test Questions 211 Programming Projects 217
CHAPTER 4
Defining Classes and Methods 221
Objectives 222 Prerequisites 222
4.1 Class and Method Definitions 222 Class Files and Separate Compilation 224 Instance Variables 225 Using Methods 228 void Method Definitions 231 Methods That Return a Value 233 The this Parameter 238 Local Variables 240 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents xxi Blocks 242 Parameters of a Primitive Type 243 Summary of Class and Method Definition Syntax 249 4.2 Information Hiding and Encapsulation 250 Information Hiding 250 Programming Tip: Parameter Names Are Local to the Method 251 Precondition and Postcondition Comments 251 The public and private Modifiers 254 Programming Tip: Instance Variables Should Be private 257 Programming Example: A Purchase Class 261 Encapsulation 265 Automatic Documentation with javadoc 268 UML Class Diagrams 268 4.3 Objects and Reference 270 Variables of a Class Type and Objects 270 Programming Example: A Species Class 279 Boolean-Valued Methods 282 Class Parameters 284 Comparing Class Parameters and Primitive-Type Parameters 287 4.4 Graphics Supplement (Optional) 291 The Graphics Class 291 Programming Example: Multiple Faces Redone with a Helping Method 294 The init Method 298 Adding Labels to an Applet 298 Chapter Summary 302 Answers to Self-Test Questions 303 Programming Projects 310
CHAPTER 5
More About Objects and Methods 315
Objectives 316 Prerequisites 316
5.1 Programming with Methods 317 Methods Calling Methods 317 Programming Tip: Make Helping Methods Private 323 5.2 Static Methods and Static Variables 326 Static Methods 326 Static Variables (Optional) 332 The Math Class 334 Integer, Double, and Other Wrapper Classes 337 5.3 Designing Methods 343 Case Study: Formatting Output 343 Top-Down Design 348 Testing Methods 350 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xxii
Table of Contents 5.4 Overloading 352 Overloading Basics 352 Programming Example: A Pet Class 355 Programming Example: A Class for Money 363 5.5 Constructors 369 Defining Constructors 370 Programming Tip: You Can Use Other Methods in a Constructor 378 5.6
Information Hiding Revisited 380
5.7 Packages 384 Packages and Importing 384 Package Names and Directories 385 Name Clashes 388 5.8 Graphics Supplement (Optional) 389 Programming Tip: Code Appearance and Actions Separately 389 Adding Buttons 390 Event-Driven Programming 391 Programming Example: A Complete Button Applet 391 Programming Buttons 392 Icons 399 Changing Visibility 401 Programming Example: An Example of Changing Visibility 401 What’s Next 405 Chapter Summary 405 Answers to Self-Test Questions 406 Programming Projects 412
CHAPTER 6
Arrays 417
Objectives 418 Prerequisites 418
6.1 Array Basics 419 Creating and Accessing Arrays 419 Array Details 420 Programming Tip: Use Singular Array Names 424 The length Instance Variable 425 Programming Tip: Use a for Loop to Step Through an Array 427 Initializing Arrays 429 6.2 Arrays in Classes and Methods 430 Case Study: Sales Report 430 Indexed Variables as Method Arguments 438 Entire Arrays as Method Arguments 440 Arguments for the Method main 441 Methods That Return Arrays 446 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents xxiii 6.3 Programming with Arrays and Classes 449 Programming Example: A Specialized List Class 450 Partially Filled Arrays 457 Searching an Array 457 6.4 Sorting Arrays 460 Selection Sort 460 Other Sorting Algorithms 465 6.5 Multidimensional Arrays 465 Multidimensional-Array Basics 467 Multidimensional-Array Parameters and Returned Values 470 Implementation of Multidimensional Arrays 471 Ragged Arrays (Optional) 475 Programming Example: Employee Time Records 476 6.6 Graphics Supplement (Optional) 482 Graphics Supplement Part 1: Text Areas and Text Fields 483 Programming Example: A Question-and-Answer Applet 483 JTextArea and JTextField Objects 483 Graphics Supplement Part 2: Drawing Polygons 487 Drawing Polygons 487 Chapter Summary 491 Answers to Self-Test Questions 492 Programming Projects 497
CHAPTER 7
Inheritance 501
Objectives 502 Prerequisites 502
7.1 Inheritance Basics 502 Programming Example: A Person Class 503 Derived Classes 504 Overriding Method Definitions 507 Overriding Versus Overloading 508 The final Modifier 508 Programming Tip: Assume That Your Coworkers Are Malicious 510 UML Inheritance Diagrams 510 7.2 Programming with Inheritance 513 Constructors in Derived Classes 513 The this Method (Optional) 514 Call to an Overridden Method 515 Programming Example: Multilevel Derived Classes 516 A Subtle Point About Overloading and Overriding (Optional) 521 Programming Tip: An Object Can Have More than One Type 522 Programming Tip: “Is a” and “Has a” Relations 525 The Class Object 526 Case Study: Character Graphics 528 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xxiv
Table of Contents Abstract Classes 538 Interfaces 542 7.3 Dynamic Binding and Polymorphism 544 Dynamic Binding 544 Type Checking and Dynamic Binding 546 Dynamic Binding with toString 547 Polymorphism 548 7.4 Graphics Supplement (Optional) 551 The Class JApplet 551 The Class JFrame 552 Window Events and Window Listeners 555 The ActionListener Interface 556 Programming Example: Happy Face as a JFrame 557 What To Do Next 558 Chapter Summary 559 Answers to Self-Test Questions 559 Programming Projects 565
CHAPTER 8
Exception Handling 569
Objectives 570 Prerequisites 570
8.1 Basic Exception Handling 571 Exceptions in Java 571 Predefined Exception Classes 583 ArrayIndexOutOfBoundsException (Alternative Ordering) 584 8.2 Defining Exception Classes 585 Defining Your Own Exception Classes 585 Programming Tip: When to Define an Exception Class 591 8.3 Using Exception Classes 596 Declaring Exceptions (Passing the Buck) 596 Exceptions That Do Not Need To Be Caught 600 The AssertionError Class (Optional) 601 Multiple Throws and Catches 601 Programming Tip: Exception Handling and Information Hiding 605 Programming Tip: When to Throw an Exception 607 The finally Block (Optional) 609 Rethrowing an Exception (Optional) 610 Case Study: A Line-Oriented Calculator 611 8.4 Graphics Supplement (Optional) 625 Exceptions in GUIs 625 Programming Example: A JFrame Using Exceptions 626 Chapter Summary 630 Answers to Self-Test Questions 630 Programming Projects 635 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents
CHAPTER 9
xxv
Streams and File I/O 641
Objectives 642 Prerequisites 642
9.1 An Overview of Streams and File I/O 643 The Concept of a Stream 643 Why Use Files for I/O? 643 Differences between Text Files and Binary Files 643 9.2 Text-File I/O 645 Text-File Output with PrintWriter 645 Text-File Input with BufferedReader 656 Programming Example: Reading a File Name from the Keyboard 660 The StringTokenizer Class 663 The Classes FileReader and FileOutputStream 667 9.3 The File Class 669 Using the File Class 669 9.4 Basic Binary-File I/O 672 Output to Binary Files, Using ObjectOutputStream 673 Some Details about writeUTF (Optional) 678 Reading Input from a Binary File, Using ObjectInputStream 679 The EOFException Class 685 The Classes FileInputStream and FileOutputStream 688 Programming Example: Processing a File of Binary Data 689 9.5 Object I/O with Object Streams 693 Binary I/O of Class Objects 693 The Serializable Interface 698 Array Objects in Binary Files 699 9.6 Graphics Supplement (Optional) 701 Programming Example: A JFrame GUI for Manipulating Files 701 Chapter Summary 707 Answers to Self-Test Questions 707 Programming Projects 713
CHAPTER 10 Dynamic Data Structures and Generics 717 Objectives 718 Prerequisites 718
10.1 Vectors 719 Using Vectors 719 Programming Tip: Adding to a Vector 726 Parameterized Classes and Generics 732 10.2 Linked Data Structures 733 Linked Lists 733 Inner Classes 744 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xxvi
Table of Contents Node Inner Classes 745 Iterators 746 Programming Tip: Internal and External Iterators 759 Exception Handling with Linked Lists 759 Variations on a Linked List 763 Other Linked Data Structures 765 10.3 Generics 765 Generic Basics 766 Programming Example: A Generic Linked List 768 Chapter Summary 774 Answers to Self-Test Questions 774 Programming Projects 783
CHAPTER 11 Recursion 787 Objectives 788 Prerequisites 788
11.1 The Basics of Recursion 788 Case Study: Digits to Words 789 How Recursion Works 794 Recursive versus Iterative Definitions 801 Recursive Methods That Return a Value 801 11.2 Programming with Recursion 806 Programming Tip: Ask Until the User Gets It Right 806 Case Study: Binary Search 808 Programming Tip: Generalize the Problem 812 Programming Example: Merge Sort—A Recursive Sorting Method 816 Chapter Summary 821 Answers to Self-Test Questions 821 Programming Projects 823
CHAPTER 12 Window Interfaces Using Swing 827 Objectives 828 Prerequisites 828
12.1 Background 829 GUIs—Graphical User Interfaces 829 Event-Driven Programming 829 12.2 Basic Swing Details 831 Programming Example: A Simple Window 832 More about Window Listeners 838 Size Units for Screen Objects 840 More on setVisible 841 Programming Example: A Better Version of Our First Swing Program 843 Programming Example: A Window with Color 846 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents xxvii Some Methods of the Class JFrame 850 Layout Managers 853 12.3 Buttons and Action Listeners 860 Programming Example: Adding Buttons 860 Buttons 862 Action Listeners and Action Events 864 Interfaces 869 The Model–View–Controller Pattern 871 12.4 Container Classes 874 The JPanel Class 874 12.5 The Container Class 877 12.6 Text I/O for GUIs 882 Text Areas and Text Fields 882 Programming Example: Labeling a Text Field 888 Inputting and Outputting Numbers 890 Programming Example: A GUI Adding Machine 893 Catching a NumberFormatException 897 Chapter Summary 900 Answers to Self-Test Questions 901 Programming Projects 909
CHAPTER 13 Applets and HTML 913 Objectives 914 Prerequisites 914
13.1 Applets 915 Applet Basics 915 Running an Applet 918 Programming Example: An Adder Applet 918 Adding Icons to an Applet 921 13.2 Introduction to HTML 924 HTML Basics 924 Programming Tip: A Simple HTML-Document Outline 926 Inserting Hyperlinks 926 Displaying a Picture 931 Programming Tip: HTML Is a Low-Level Language 932 13.3 Applets in HTML 932 Placing an Applet in an HTML Document 932 The Older Applet Class (Optional) 935 Applets and Security 936 Chapter Summary 937 Answers to Self-Test Questions 937 Programming Projects 938 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
xxviii
Table of Contents
CHAPTER 14 More Swing 941 Objectives 942 Prerequisites 942
14.1 Menus 942 Programming Example: A GUI with a Menu 943 Menu Bars, Menus, and Menu Items 943 Nested Menus 948 14.2 Making GUIs Pretty (and More Functional) 950 Adding Icons 950 The JScrollPane Class for Scroll Bars 957 Adding Borders 963 14.3 More Layout Managers 969 The BoxLayout Manager Class 969 Struts and Glue 973 Setting the Spacing between Components 975 The Box Container Class 975 The CardLayout Manager 978 14.4 Inner Classes 984 Helping Classes 984 14.5 More on Events and Listeners 986 The WindowListener Interface 986 Programming Example: Components with Changing Visibility 997 Some More Details on Updating a GUI 1000 14.6 Another Look at the Swing Class Hierarchy 1001 Buttons, Menus, and Abstract Buttons 1001 Chapter Summary 1004 Answers to Self-Test Questions 1004 Programming 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 1027 Percent Notation 1027 Scientific Notation (E-Notation) 1029
Appendix 18 The Iterator Interface 1030 Appendix 19 Cloning 1031 Appendix 20 Javadoc 1034 PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents xxix Commenting Classes for Use with javadoc 1034 Running javadoc 1035
Appendix 21 The JOptionPane Class 1036 A Sample Program Using JOptionPane 1036 Multiline Output Windows 1041
Appendix 22 Differences between C++ and Java 1042 Primitive Types 1042 Strings 1042 Flow of Control 1042 Testing for Equality 1043 main Method (Function) and Other Methods 1043 Files and Including Files 1043 Class and Method (Function) Definitions 1043 No Pointers in Java 1043 Method (Function) Parameters 1044 Arrays 1044 Garbage Collection 1044 Other Comparisons 1044
Index 1045
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).
Table of Contents
xxx
PRELIMINARY PROOFS © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher. For the exclusive use of adopters of the book JAVA: An Introduction to Problem Solving and Programming, Fourth Edition (ISBN: 0-13-149202-0).