Tải bản đầy đủ (.pdf) (1,947 trang)

Tài liệu introduction to java progamming comprehesive 9th pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (28.41 MB, 1,947 trang )

ALWAYS LEARNING
PEARSON
Learn more at www.myprogramminglab.com
MyProgrammingLab™
Through the power of practice and immediate personalized
feedback, MyProgrammingLab improves your performance.
get with the programming
This page intentionally left blank
INTRODUCTION TO
JAVA
TM
PROGRAMMING
COMPREHENSIVE VERSION
Ninth Edition
Y. Daniel Liang
Armstrong Atlantic State University
Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Editorial Director: Marcia Horton
Editor in Chief: Michael Hirsch
Executive Editor: Tracy Dunkelberger
Associate Editor: Carole Snyder
Director of Marketing: Patrice Jones
Marketing Manager: Yez Alayan
Marketing Coordinator: Kathryn Ferranti
Marketing Assistant: Emma Snider
Director of Production: Vince O’Brien
Managing Editor: Jeff Holcomb
Production Project Manager: Kayla Smith-Tarbox


Operations Supervisor: Alan Fischer
Manufacturing Buyer: Lisa McDowell
Art Director: Anthony Gemmellaro
Cover Designer: Anthony Gemmellaro
Manager, Visual Research: Karen Sanatar
Manager, Rights and Permissions: Mike Joyce
Text Permission Coordinator: Danielle Simon
and Jenn Kennett
Cover Illustration: Jason Consalvo
Lead Media Project Manager: Daniel Sandin
Project Management: Gillian Hall
Composition and Art: Laserwords
Printer/Binder: Edwards Brothers
Cover Printer: Lehigh-Phoenix Color/Hagerstown
Text Font: Times 10/12
10 9 8 7 6 5 4 3 2 1
ISBN 13: 978-0-13-293652-1
ISBN 10: 0-13-293652-6
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook
appear on the appropriate page within text and as follows: Table 3.2 and 10.1: Data from IRS. Figures 8.1, 8.12,
12.3, 12.5, 12.7, 12.9, 12.10, 12.12–12.21, 12.26–12.30, 13.1, 13.4, 13.9, 13.11, 13.15, 13.17, 13.19, 13.21, 13.23,
13.25–13.35, 14.10, 14.14,15.9–15.11, 16.1, 16.2, 16.8, 16.11, 16.14, 16.17, 16.19–16.35, 17.1, 17.3, 17.6, 17.9,
17.12, 17.13, 17.15, 17.17–17.32, 18.6–18.8, 18.10, 18.15–18.35, 19.19, 19.20, 19.22, 20.1, 20.9, 20.12–20.14,
20.16–20.20, 22.8, 22.17–22.21, 24.4, 24.6, 24.8, 24.11–24.17, 25.18–25.20, 27.17, 27.23-–27.25, 30.10, 30.14,
30.22, 30.23, 30.25, 31.24–31.26, 32.6, 32.7, 32.31–32.34, 33.5, 33.9–33.11, 33.16–33.22, 34.23, 34.27–34.30:
Screenshots © 2011 by Oracle Corporation. Reprinted with permission.
Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other coun-
tries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This book is not sponsored
or endorsed by or affiliated with the Microsoft Corporation.
Copyright © 2013, 2011, 2009, 2007, 2004 by Pearson Education, Inc., publishing as Prentice Hall. All rights

reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permis-
sion should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain
permission(s) to use material from this work, please submit a written request to Pearson Education, Inc.,
Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to
201-236-3290.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations
have been printed in initial caps or all caps.
Library of Congress Cataloging-in-Publication Data available upon request.
This book is dedicated to Professor Myers Foreman. Myers
used this book in CS1, CS2, and CS3 at Lamar University
and provided invaluable suggestions for improving the book.
Sadly, Myers passed away after he completed the review
of this edition.
To Samantha, Michael, and Michelle
This page intentionally left blank
PREFACE
Dear Reader,
Many of you have provided feedback on earlier editions of this book, and your comments and
suggestions have greatly improved the book. This edition has been substantially enhanced in
presentation, organization, examples, exercises, and supplements. We have:
■ Reorganized sections and chapters to present the subjects in a more logical order
■ Included many new interesting examples and exercises to stimulate interests
■ Updated to Java 7
■ Created animations for algorithms and data structures to visually demonstrate the
concepts
■ Redesigned the support Website to make it easier to navigate
This book teaches programming in a problem-driven way that focuses on problem solving
rather than syntax. We make introductory programming interesting by using thought-provoking

problems in a broad context. The central thread of early chapters is on problem solving.
Appropriate syntax and library are introduced to enable readers to write programs for solving the
problems. To support the teaching of programming in a problem-driven way, the book provides
a wide variety of problems at various levels of difficulty to motivate students. To appeal to stu-
dents in all majors, the problems cover many application areas, including math, science, business,
financial, gaming, animation, and multimedia.
The book focuses on fundamentals first by introducing basic programming concepts and
techniques before designing custom classes. The fundamental concepts and techniques of loops,
methods, and arrays are the foundation for programming. Building this strong foundation
prepares students to learn object-oriented programming and advanced Java programming.
This comprehensive version covers fundamentals of programming, object-oriented program-
ming, GUI programming, algorithms and data structures, concurrency, networking, internation-
alization, advanced GUI, database, and Web programming. It is designed to prepare students to
become proficient Java programmers. A brief version (Introduction to Java Programming, Brief
Version, Ninth Edition) is available for a first course on programming, commonly known as
CS1. The brief version contains the first 20 chapters of the comprehensive version.
The best way to teach programming is by example, and the only way to learn programming
is by doing. Basic concepts are explained by example, and a large number of exercises with
various levels of difficulty are provided for students to practice. For our programming courses,
we assign programming exercises after each lecture.
Our goal is to produce a text that teaches problem solving and programming in a broad
context using a wide variety of interesting examples. If you have any comments on and
suggestions for improving the book, please email me.
Sincerely,
Y. Daniel Liang

www.cs.armstrong.edu/liang
www.pearsonhighered.com/liang
vii
brief version

comprehensive version
fundamentals-first
problem-driven
what is new?
examples and exercises
viii Preface
What’s New in This Edition?
This edition substantially improves Introduction to Java Programming, Eighth Edition. The
major improvements are as follows:
■ This edition is completely revised in every detail to enhance clarity, presentation, content,
examples, and exercises.
■ New examples and exercises are provided to motivate and stimulate student interest in
programming.
■ Each section starts with a Key Point that highlights the important concepts covered in the
section.
■ Check Points provide review questions to help students track their progress and evaluate
their learning after a major concept or example is covered.
■ Each chapter provides test questions online. They are grouped by sections for students to
do self-test. The questions are graded online.
■ New VideoNotes provide short video tutorials designed to reinforce code.
■ The Java GUI API is an excellent example of how the object-oriented principle is applied.
Students learn better with concrete and visual examples. So basic GUI/Graphics is moved
before introducing abstract classes and interfaces. You can however still choose to cover
abstract classes and interfaces before GUI or skip GUI.
■ The numeric wrapper classes, BigInteger, and BigDecimal are now introduced in
Chapter 10 to enable students to write code using these classes early.
■ Exception handling is covered before abstract classes and interfaces so that students
can build robust programs early. The instructor can still choose to cover exception
handling later. Text I/O is now combined with exception handling to form a new
chapter.

■ Simple use of generics is introduced along with ArrayList in Chapter 11 and with
Comparable in Chapter 15 while the complex detail on generics is still kept in
Chapter 21.
■ Chapter 22 is split into two chapters (Chapter 22 and Chapter 23) to make room for incor-
porating three new case studies to demonstrate effective use of data structures.
■ Chapter 24 is expanded to introduce algorithmic techniques: dynamic programming,
divide-and-conquer, backtracking, and greedy algorithm with new examples to design
efficient algorithms.
■ Visual animations are created to show how data structures and algorithms work.
■ A common problem with a data structures course is lack of good examples and exercises.
This edition added many new interesting examples and exercises.
■ Parallel programming techniques are introduced in Chapter 32, Multithreading and
Parallel Programming.
■ Chapter 44 is completely new to introduce the latest standard on JSF.
■ Chapter 50 is completely new to introduce testing using JUnit.
Please visit
www.cs.armstrong.edu/liang/intro9e/newfeatures.html for a complete list of new
features as well as correlations to the previous edition.
new JUnit chapter
new JSF chapter
parallel programming
new data structures materials
data structures and algorithm
animation
developing efficient
algorithms
splitting Chapter 22
simple generics early
exception handling earlier
numeric classes covered early

basic GUI and graphics early
test questions
check point
key point
new problems
complete revision
VideoNotes
Preface ix
Pedagogical Features
The book uses the following elements to help students get the most from the material:
■ The Objectives at the beginning of each chapter list what students should learn from the
chapter. This will help them determine whether they have met the objectives after com-
pleting the chapter.
■ The Introduction opens the discussion with representative problems to give the reader an
overview of what to expect from the chapter.
■ Key Points highlight the important concepts covered in each section.
■ Check Points provide review questions to help students track their progress as they read
through the chapter and evaluate their learning.
■ Problems and Case Studies, carefully chosen and presented in an easy-to-follow style,
teach problem solving and programming concepts. The book uses many small, simple,
and stimulating examples to demonstrate important ideas.
■ The Chapter Summary reviews the important subjects that students should understand
and remember. It helps them reinforce the key concepts they have learned in the chapter.
■ Test Questions are accessible online, grouped by sections, for students to do self-test on
programming concepts and techniques.
■ Programming Exercises are grouped by sections to provide students with opportunities to
apply the new skills they have learned on their own. The level of difficulty is rated as easy (no
asterisk), moderate (*), hard (**), or challenging (***). The trick of learning programming
is practice, practice, and practice. To that end, the book provides a great many exercises.
■ Notes, Tips, Cautions, and Design Guides are inserted throughout the text to offer valu-

able advice and insight on important aspects of program development.
Note
Provides additional information on the subject and reinforces important concepts.
Tip
Teaches good programming style and practice.
Caution
Helps students steer away from the pitfalls of programming errors.
Design Guide
Provides guidelines for designing programs.
Flexible Chapter Orderings
The book is designed to provide flexible chapter orderings to enable GUI, exception handling,
recursion, generics, and the Java Collections Framework to be covered earlier or later. The
diagram on the next page shows the chapter dependencies.
Organization of the Book
The chapters can be grouped into five parts that, taken together, form a comprehensive intro-
duction to Java programming, data structures and algorithms, and database and Web pro-
gramming. Because knowledge is cumulative, the early chapters provide the conceptual basis
Chapter 45 Web Services
Chapter 44 Java Server Faces
Chapter 46 Remote Method
Invocation
Chapter 27 Binary Search Trees
Chapter 28 Hashing
Chapter 29 AVL Trees
Chapter 31 Weighted Graphs and
Applications
Chapter 30 Graphs and
Applications
Chapter 23 Sets and Maps
Chapter 24 Developping

Efficient Algorithms
Chapter 1 Introduction to
Computers, Programs, and
Java
Chapter 2 Elementary
Programming
Chapter 4 Loops
Chapter 5 Methods
Chapter 7 Multidimensional
Arrays
Part I: Fundamentals of
Programming
Chapter 3 Selections
Chapter 8 Objects and Classes
Chapter 19 Binary I/O
Note: Chapters 1–20 are in the
brief version of this book.
Note: Chapters 1–34 are in the
comprehensive version.
Note: Chapters 35–50 are bonus
chapters available from the
Companion Website.
Chapter 9 Strings
Chapter 10 Thinking in Objects
Chapter 11 Inheritance and
Polymorphism
Chapter 14 Exception
Handling and Text I/O
Chapter 15 Abstract Classes
and Interfaces

Chapter 6 Single-Dimensional
Arrays
Part II: Object-Oriented
Programming
Chapter 32 Multithreading and
Parallel Programming
Chapter 42 Servlets
Chapter 33 Networking
Chapter 34 Java Database
Programming
Chapter 35 Internationalization
Chapter 41 Advanced
Database Programming
Chapter 43 Java Server Pages
Part V: Advanced Java
Programming
Chapter 12 GUI Basics
Chapter 13 Graphics
Chapter 16 Event-Driven
Programming
Chapter 22 Lists, Stacks, Queues,
and Priority Queues
Chapter 17 GUI Components
Chapter 18 Applets and
Multimedia
Chapter 36 JavaBeans and Bean
Events
Chapter 37 Containers, Layout
Managers, and Borders
Chapter 38 Menus, Toolbars,

and Dialogs
Chapter 39 MVC and Swing
Models
Chapter 40 JTable and JTree
Chapter 49 Java 2D
Chapter 50 Testing Using JUnit
Part III: GUI Programming
Chapter 20 RecursionCh 6
Chapter 21 Generics
Chapter 26 Implementing Lists,
Stacks, Queues, and Priority
Queues
Part IV: Data Structures and
Algorithms
Ch 8
Ch 15
Ch 18
Chapter 47 2-4 Trees and B-
Trees
Chapter 48 Red-Black Trees
Chapter 25 Sorting
x Preface
for understanding programming and guide students through simple examples and exercises;
subsequent chapters progressively present Java programming in detail, culminating with the
development of comprehensive Java applications. The appendixes contain a mixed bag of top-
ics, including an introduction to number systems and bitwise operations.
Part I: Fundamentals of Programming (Chapters 1–7)
The first part of the book is a stepping stone, preparing you to embark on the journey of
learning Java. You will begin to learn about Java (Chapter 1) and fundamental programming
techniques with primitive data types, variables, constants, assignments, expressions, and

operators (Chapter 2), control statements (Chapters 3–4), methods (Chapter 5), and arrays
(Chapters 6–7). After Chapter 6, you can jump to Chapter 20 to learn how to write recursive
methods for solving inherently recursive problems.
Part II: Object-Oriented Programming (Chapters 8–11, 14–15, and 19)
This part introduces object-oriented programming. Java is an object-oriented programming
language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great
flexibility, modularity, and reusability in developing software. You will learn programming
with objects and classes (Chapters 8–10), class inheritance (Chapter 11), polymorphism
(Chapter 11), exception handling and text I/O (Chapter 14), abstract classes (Chapter 15), and
interfaces (Chapter 15). Processing strings is introduced in Chapter 9, and binary I/O is dis-
cussed in Chapter 19.
Part III: GUI Programming (Chapters 12–13, 16–18, and Bonus Chapters 36–40 and 49)
This part introduces elementary Java GUI programming in Chapters 12–13 and 16–18 and
advanced Java GUI programming in Chapters 36–40 and 49. Major topics include GUI basics
(Chapter 12), drawing shapes (Chapter 13), event-driven programming (Chapter 16), using GUI
components (Chapter 17), and writing applets (Chapter 18). You will learn the architecture of
Java GUI programming and use the GUI components to develop applications and applets from
these elementary GUI chapters. The advanced GUI chapters discuss Java GUI programming in
more depth and breadth. You will delve into JavaBeans and learn how to develop custom events
and source components in Chapter 36, review and explore new containers, layout managers,
and borders in Chapter 37, learn how to create GUI with menus, popup menus, toolbars,
dialogs, and internal frames in Chapter 38, develop components using the MVC approach and
explore the advanced Swing components JSpinner, JList, and JComboBox in Chapter 39,
and JTable and JTree in Chapter 40. Chapter 49 introduces Java 2D.
Part IV: Data Structures and Algorithms (Chapters 20–31 and Bonus Chapters 47–48)
This part covers the main subjects in a typical data structures course. Chapter 20 introduces
recursion to write methods for solving inherently recursive problems. Chapter 21 presents
how generics can improve software reliability. Chapters 22 and 23 introduce the Java
Collection Framework, which defines a set of useful API for data structures. Chapter 24 dis-
cusses measuring algorithm efficiency in order to choose an appropriate algorithm for appli-

cations. Chapter 25 describes classic sorting algorithms. You will learn how to implement
several classic data structures lists, queues, and priority queues in Chapter 26. Chapters 27
and 29 introduce binary search trees and AVL trees. Chapter 28 presents hashing and imple-
menting maps and sets using hashing. Chapters 30 and 31 introduce graph applications. The
2-4 trees, B-trees, and red-black trees are covered in Chapters 47–48.
Part V: Advanced Java Programming (Chapters 32–33 and Bonus Chapters 35, 41–46,
and 50)
This part of the book is devoted to advanced Java programming. Chapter 32 treats the use
of multithreading to make programs more responsive and interactive and introduces par-
allel programming. Chapter 33 discusses how to write programs that talk with each other
Preface xi
over the Internet. Chapter 34 introduces the use of Java to develop database projects, and
Chapter 35 covers the use of internationalization support to develop projects for interna-
tional audiences. Chapter 41 delves into advanced Java database programming. Bonus
Chapters 42, 43 and 44 introduce how to use Java servlets, JavaServer Pages, and
JavaServer Faces to generate dynamic content from Web servers. Chapter 45 discusses
Web services, and Chapter 46 introduces remote method invocation. Chapter 50 introduces
testing Java programs using JUnit.
Appendixes
This part of the book covers a mixed bag of topics. Appendix A lists Java keywords.
Appendix B gives tables of ASCII characters and their associated codes in decimal and in
hex. Appendix C shows the operator precedence. Appendix D summarizes Java modifiers and
their usage. Appendix E discusses special floating-point values. Appendix F introduces num-
ber systems and conversions among binary, decimal, and hex numbers. Finally, Appendix G
introduces bitwise operations.
Java Development Tools
You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs
and to compile and run the programs from the command window. You can also use a Java
development tool, such as TextPad, NetBeans, or Eclipse. These tools support an integrated
development environment (IDE) for developing Java programs quickly. Editing, compiling,

building, executing, and debugging programs are integrated in one graphical user interface.
Using these tools effectively can greatly increase your programming productivity. TextPad is
a primitive IDE tool. NetBeans and Eclipse are more sophisticated, but they are easy to use if
you follow the tutorials. Tutorials on TextPad, NetBeans, and Eclipse can be found in the sup-
plements on the Companion Website www.cs.armstrong.edu/liang/intro9e.
Online Practice and Assessment with
MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of program-
ming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab
improves the programming competence of beginning students who often struggle with the
basic concepts and paradigms of popular high-level programming languages.
A self-study and homework tool, a MyProgrammingLab course consists of hundreds
of small practice problems organized around the structure of this textbook. For students, the
system automatically detects errors in the logic and syntax of their code submissions and
offers targeted hints that enable students to figure out what went wrong—and why. For
instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the
code inputted by students for review.
MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the
makers of the CodeLab interactive programming exercise system. For a full demonstration, to
see feedback from instructors and students, or to get started using MyProgrammingLab in
your course, visit www.myprogramminglab.com.
VideoNotes
We are excited about the new VideoNotes feature that is found in this new edition. These videos
provide additional help by presenting examples of key topics and showing how to solve problems
completely, from design through coding. VideoNotes are free to first time users and can be
accessed by redeeming the access code in the front of this book at
www.pearsonhighered.com/liang.
IDE tutorials
xii Preface
VideoNote

LiveLab
This book is accompanied by a complementary Web-based course assessment and manage-
ment system for instructors. The system has four main components:
■ The Automatic Grading System can automatically grade programs.
■ The Quiz Creation/Submission/Grading System enables instructors to create and
modify quizzes that students can take and be graded upon automatically.
■ The Peer Evaluation System enables peer evaluations.
■ Tracking grades, attendance, etc., lets students track their grades, and enables instruc-
tors to view the grades of all students and to track students’ attendance.
The main features of the Automatic Grading System include:
■ Students can run and submit exercises. (The system checks whether their program runs
correctly—students can continue to run and resubmit the program before the due date.)
■ Instructors can review submissions, run programs with instructor test cases, correct them,
provide feedback to students, and check plagiarism.
■ Instructors can create/modify their own exercises, create public and secret test cases,
assign exercises, and set due dates for the whole class or for individuals.
■ Instructors can assign all the exercises in the text to students. Additionally, LiveLab
provides extra exercises that are not printed in the text.
■ Instructors can sort and filter all exercises and check grades (by time frame, student,
and/or exercise).
■ Instructors can delete students from the system.
■ Students and instructors can track grades on exercises.
The main features of the Quiz System are:
■ Instructors can create/modify quizzes from the test bank or a text file or create completely
new tests online.
■ Instructors can assign the quizzes to students and set a due date and test time limit for the
whole class or for individuals.
■ Students and instructors can review submitted quizzes.
■ Instructors can analyze quizzes and identify students’ weaknesses.
■ Students and instructors can track grades on quizzes.

The main features of the Peer Evaluation System include:
■ Instructors can assign peer evaluation for programming exercises.
■ Instructors can view peer evaluation reports.
Student Resource Website
The Student Resource Website (www.cs.armstrong.edu/liang/intro9e) contains the following
resources:
■ Access to VideoNotes (www.pearsonhighered.com/liang).
■ Answers to check point questions
Preface xiii
■ Solutions to even-numbered programming exercises
■ Source code for the examples in the book
■ Interactive self-testing (organized by sections for each chapter)
■ Data structures and algorithm animations
■ Errata
Instructor Resource Website
The Instructor Resource Website, accessible from www.cs.armstrong.edu/liang/intro9e, contains
the following resources:
■ Microsoft PowerPoint slides with interactive buttons to view full-color, syntax-highlighted
source code and to run programs without leaving the slides.
■ Solutions to all programming exercises. Students will have access to the solutions of even-
numbered programming exercises.
■ Web-based quiz generator. (Instructors can choose chapters to generate quizzes from a
large database of more than two thousand questions.)
■ Sample exams. Most exams have four parts:
■ Multiple-choice questions or short-answer questions
■ Correct programming errors
■ Trace programs
■ Write programs
■ Projects. In general, each project gives a description and asks students to analyze, design,
and implement the project.

Some readers have requested the materials from the Instructor Resource Website. Please
understand that these are for instructors only. Such requests will not be answered.
Algorithm Animations
We have provided numerous animations for algorithms. These are valuable pedagogical tools
to demonstrate how algorithms work. Algorithm animations can be accessed from the
Companion Website.
Acknowledgments
I would like to thank Armstrong Atlantic State University for enabling me to teach what I
write and for supporting me in writing what I teach. Teaching is the source of inspiration for
continuing to improve the book. I am grateful to the instructors and students who have offered
comments, suggestions, bug reports, and praise.
This book has been greatly enhanced thanks to outstanding reviews for this and previous edi-
tions. The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed (North
Georgia College and State University), Omar Aldawud (Illinois Institute of Technology), Yang
Ang (University of Wollongong, Australia), Kevin Bierre (Rochester Institute of Technology),
David Champion (DeVry Institute), James Chegwidden (Tarrant County College), Anup Dargar
(University of North Dakota), Charles Dierbach (Towson University), Frank Ducrest
(University of Louisiana at Lafayette), Erica Eddy (University of Wisconsin at Parkside), Deena
xiv Preface
Engel (New York University), Henry A. Etlinger (Rochester Institute of Technology), James
Ten Eyck (Marist College), Myers Foreman (Lamar University), Olac Fuentes (University of
Texas at El Paso), Edward F. Gehringer (North Carolina State University), Harold Grossman
(Clemson University), Barbara Guillot (Louisiana State University), Stuart Hansen (University
of Wisconsin, Parkside), Dan Harvey (Southern Oregon University), Ron Hofman (Red River
College, Canada), Stephen Hughes (Roanoke College), Vladan Jovanovic (Georgia Southern
University), Edwin Kay (Lehigh University), Larry King (University of Texas at Dallas), Nana
Kofi (Langara College, Canada), George Koutsogiannakis (Illinois Institute of Technology),
Roger Kraft (Purdue University at Calumet), Norman Krumpe (Miami University), Hong Lin
(DeVry Institute), Dan Lipsa (Armstrong Atlantic State University), James Madison
(Rensselaer Polytechnic Institute), Frank Malinowski (Darton College), Tim Margush

(University of Akron), Debbie Masada (Sun Microsystems), Blayne Mayfield (Oklahoma
State University), John McGrath (J.P. McGrath Consulting), Hugh McGuire (Grand Valley
State), Shyamal Mitra (University of Texas at Austin), Michel Mitri (James Madison
University), Kenrick Mock (University of Alaska Anchorage), Frank Murgolo (California State
University, Long Beach), Jun Ni (University of Iowa), Benjamin Nystuen (University of
Colorado at Colorado Springs), Maureen Opkins (CA State University, Long Beach), Gavin
Osborne (University of Saskatchewan), Kevin Parker (Idaho State University), Dale Parson
(Kutztown University), Mark Pendergast (Florida Gulf Coast University), Richard Povinelli
(Marquette University), Roger Priebe (University of Texas at Austin), Mary Ann Pumphrey (De
Anza Junior College), Pat Roth (Southern Polytechnic State University), Amr Sabry (Indiana
University), Carolyn Schauble (Colorado State University), David Scuse (University of
Manitoba), Ashraf Shirani (San Jose State University), Daniel Spiegel (Kutztown University),
Joslyn A. Smith (Florida Atlantic University) , Lixin Tao (Pace University), Ronald F. Taylor
(Wright State University), Russ Tront (Simon Fraser University), Deborah Trytten (University
of Oklahoma), Kent Vidrine (George Washington University), and Bahram Zartoshty
(California State University at Northridge).
It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank
Tracy Dunkelberger and her colleagues Marcia Horton, Michael Hirsch, Matt Goldstein,
Carole Snyder, Tim Huddleston, Yez Alayan, Jeff Holcomb, Kayla Smith-Tarbox, Gillian
Hall, Rebecca Greenberg, and their colleagues for organizing, producing, and promoting this
project.
As always, I am indebted to my wife, Samantha, for her love, support, and encouragement.
Preface xv
BRIEF CONTENTS
1 Introduction to Computers, Programs,
and Java 1
2 Elementary Programming 33
3 Selections 81
4 Loops 133
5 Methods 177

6 Single-Dimensional Arrays 223
7 Multidimensional Arrays 263
8 Objects and Classes 295
9 Strings 335
10 Thinking in Objects 369
11 Inheritance and Polymorphism 407
12 GUI Basics 445
13 Graphics 479
14 Exception Handling and Text I/O 517
15 Abstract Classes and Interfaces 559
16 Event-Driven Programming 599
17 GUI Components 639
18 Applets and Multimedia 671
19 Binary I/O 709
20 Recursion 737
21 Generics 769
22 Lists, Stacks, Queues, and Priority
Queues 793
23 Sets and Maps 829
24 Developing Efficient Algorithms 853
25 Sorting 893
26 Implementing Lists, Stacks, Queues,
and Priority Queues 927
27 Binary Search Trees 961
28 Hashing 997
29 AVL Trees 1027
30 Graphs and Applications 1047
31 Weighted Graphs and Applications 1093
32 Multithreading and Parallel
Programming 1129

33 Networking 1175
34 Java Database Programming 1211
Chapters 35–50 are bonus Web chapters
35
Internationalization 35-1
36 JavaBeans 36-1
37 Containers, Layout Managers,
and Borders 37-1
38 Menus, Toolbars, and Dialogs 38-1
39 MVC and Swing Models 39-1
40 JTable and JTree 40-1
41 Advanced Database Programming 41-1
42 Servlets 42-1
43 JavaServer Pages 43-1
44 JavaServer Faces 44-1
45 Web Services 45-1
46 Remote Method Invocation 46-1
47 2-4 Trees and B-Trees 47-1
48 Red-Black Trees 48-1
49 Java 2D 49-1
50 Testing Using JUnit 50-1
APPENDIXES
A Java Keywords 1251
B The ASCII Character Set 1254
C Operator Precedence Chart 1256
D Java Modifiers 1258
E Special Floating-Point Values 1260
F Number Systems 1261
G Bitwise Operatoirns 1265
INDEX 1267

xvi
CONTENTS
Chapter 1 Introduction to Computers, Programs,
and Java
1
1.1 Introduction 2
1.2 What Is a Computer? 2
1.3 Programming Languages 9
1.4 Operating Systems 12
1.5 Java, the World Wide Web, and Beyond 13
1.6 The Java Language Specification, API, JDK, and IDE 16
1.7 A Simple Java Program 16
1.8 Creating, Compiling, and Executing a Java Program 19
1.9 Displaying Text in a Message Dialog Box 22
1.10 Programming Style and Documentation 24
1.11 Programming Errors 26
Chapter 2 Elementary Programming 33
2.1 Introduction 34
2.2 Writing a Simple Program 34
2.3 Reading Input from the Console 37
2.4 Identifiers 40
2.5 Variables 40
2.6 Assignment Statements and Assignment Expressions 42
2.7 Named Constants 43
2.8 Naming Conventions 44
2.9 Numeric Data Types and Operations 44
2.10 Numeric Literals 48
2.11 Evaluating Expressions and Operator Precedence 50
2.12 Case Study: Displaying the Current Time 51
2.13 Augmented Assignment Operators 53

2.14 Increment and Decrement Operators 54
2.15 Numeric Type Conversions 56
2.16 Software Development Process 58
2.17 Character Data Type and Operations 62
2.18 The String Type 68
2.19 Getting Input from Input Dialogs 70
Chapter 3 Selections 81
3.1 Introduction 82
3.2
boolean Data Type 82
xvii
3.3 if Statements 84
3.4 Case Study: Guessing Birthdays 86
3.5 Two-Way if-else Statements 89
3.6 Nested
if and Multi-Way if-else Statements 91
3.7 Common Errors in Selection Statements 93
3.8 Generating Random Numbers 96
3.9 Case Study: Computing Body Mass Index 97
3.10 Case Study: Computing Taxes 99
3.11 Logical Operators 101
3.12 Case Study: Determining Leap Year 105
3.13 Case Study: Lottery 106
3.14 switch Statements 108
3.15 Conditional Expressions 111
3.16 Formatting Console Output 112
3.17 Operator Precedence and Associativity 115
3.18 Confirmation Dialogs 117
3.19 Debugging 119
Chapter 4 Loops 133

4.1 Introduction 134
4.2 The while Loop 134
4.3 The do-while Loop 144
4.4 The for Loop 146
4.5 Which Loop to Use? 150
4.6 Nested Loops 152
4.7 Minimizing Numeric Errors 154
4.8 Case Studies 155
4.9 Keywords
break
and
continue
159
4.10 Case Study: Displaying Prime Numbers 162
4.11 Controlling a Loop with a Confirmation Dialog 164
Chapter 5 Methods 177
5.1 Introduction 178
5.2 Defining a Method 178
5.3 Calling a Method 180
5.4 void Method Example 183
5.5 Passing Parameters by Values 186
5.6 Modularizing Code 189
5.7 Case Study: Converting Decimals to Hexadecimals 191
5.8 Overloading Methods 193
5.9 The Scope of Variables 196
5.10 The
Math Class 197
xviii Contents
5.11 Case Study: Generating Random Characters 201
5.12 Method Abstraction and Stepwise Refinement 203

Chapter 6 Single-Dimensional Arrays 223
6.1 Introduction 224
6.2 Array Basics 224
6.3 Case Study: Lotto Numbers 231
6.4 Case Study: Deck of Cards 234
6.5 Copying Arrays 236
6.6 Passing Arrays to Methods 237
6.7 Returning an Array from a Method 240
6.8 Case Study: Counting the Occurrences of Each Letter 241
6.9 Variable-Length Argument Lists 244
6.10 Searching Arrays 245
6.11 Sorting Arrays 248
6.12 The
Arrays Class 252
Chapter 7 Multidimensional Arrays 263
7.1 Introduction 264
7.2 Two-Dimensional Array Basics 264
7.3 Processing Two-Dimensional Arrays 267
7.4 Passing Two-Dimensional Arrays to Methods 269
7.5 Case Study: Grading a Multiple-Choice Test 270
7.6 Case Study: Finding the Closest Pair 272
7.7 Case Study: Sudoku 274
7.8 Multidimensional Arrays 277
Chapter 8 Objects and Classes 295
8.1 Introduction 296
8.2 Defining Classes for Objects 296
8.3 Example: Defining Classes and Creating Objects 298
8.4 Constructing Objects Using Constructors 303
8.5 Accessing Objects via Reference Variables 304
8.6 Using Classes from the Java Library 308

8.7 Static Variables, Constants, and Methods 312
8.8 Visibility Modifiers 317
8.9 Data Field Encapsulation 319
8.10 Passing Objects to Methods 322
8.11 Array of Objects 326
Chapter 9 Strings 335
9.1 Introduction 336
9.2 The
String Class 336
Contents xix
9.3 Case Study: Checking Palindromes 347
9.4 Case Study: Converting Hexadecimals to Decimals 348
9.5 The Character Class 350
9.6 The
StringBuilder and StringBuffer 353
9.7 Command-Line Arguments 358
Chapter 10 Thinking in Objects 369
10.1 Introduction 370
10.2 Immutable Objects and Classes 370
10.3 The Scope of Variables 371
10.4 The
this Reference 373
10.5 Class Abstraction and Encapsulation 375
10.6 Object-Oriented Thinking 379
10.7 Object Composition 382
10.8 Case Study: Designing the Course Class 384
10.9 Case Study: Designing a Class for Stacks 386
10.10 Case Study: Designing the GuessDate Class 388
10.11 Class Design Guidelines 391
10.12 Processing Primitive Data Type Values as Objects 393

10.13 Automatic Conversion between Primitive Types
and Wrapper Class Types 396
10.14 The BigInteger and BigDecimal 397
Chapter 11 Inheritance and Polymorphism 407
11.1 Introduction 408
11.2 Superclasses and Subclasses 408
11.3 Using the super Keyword 414
11.4 Overriding Methods 418
11.5 Overriding vs. Overloading 418
11.6 The Object Class and Its toString() 420
11.7 Polymorphism 421
11.8 Dynamic Binding 422
11.9 Casting Objects and the instanceof Operator 425
11.10 The Object’s equals method 429
11.11 The ArrayList Class 430
11.12 Case Study: A Custom Stack Class 436
11.13 The protected Data and Methods 437
11.14 Preventing Extending and Overriding 439
Chapter 12 GUI Basics 445
12.1 Introduction 446
12.2 Swing vs. AWT 446
xx Contents
12.3 The Java GUI API 446
12.4 Frames 449
12.5 Layout Managers 451
12.6 Using Panels as Subcontainers 458
12.7 The
Color Class 460
12.8 The Font Class 461
12.9 Common Features of Swing GUI Components 462

12.10 Image Icons 465
12.11 JButton 467
12.12 JCheckBox 471
12.13 JRadioButton 472
12.14 Labels 473
12.15 Text Fields 474
Chapter 13 Graphics 479
13.1 Introduction 480
13.2 The Graphics Class 480
13.3 Drawing Strings, Lines, Rectangles, and Ovals 483
13.4 Case Study: The FigurePanel Class 485
13.5 Drawing Arcs 488
13.6 Drawing Polygons and Polylines 490
13.7 Centering a String Using the FontMetrics Class 493
13.8 Case Study: The MessagePanel Class 495
13.9 Case Study: The StillClock Class 500
13.10 Displaying Images 504
13.11 Case Study: The ImageViewer Class 506
Chapter 14 Exception Handling and Text I/O 517
14.1 Introduction 518
14.2 Exception-Handling Overview 518
14.3 Exception Types 523
14.4 More on Exception Handling 526
14.5 The finally Clause 534
14.6 When to Use Exceptions 535
14.7 Rethrowing Exceptions 536
14.8 Chained Exceptions 537
14.9 Defining Custom Exception Classes 538
14.10 The File Class 541
14.11 File Input and Output 544

14.12 File Dialogs 549
14.13 Reading Data from the Web 551
Contents xxi
Chapter 15 Abstract Classes and Interfaces 559
15.1 Introduction 560
15.2 Abstract Classes 560
15.3 Case Study: the Abstract Number Class 565
15.4 Case Study: Calendar and GregorianCalendar 567
15.5 Interfaces 570
15.6 The Comparable Interface 573
15.7 The Cloneable Interface 577
15.8 Interfaces vs. Abstract Classes 581
15.9 Case Study: The Rational Class 584
Chapter 16 Event-Driven Programming 599
16.1 Introduction 600
16.2 Events and Event Sources 602
16.3 Listeners, Registrations, and Handling Events 603
16.4 Inner Classes 608
16.5 Anonymous Class Listeners 609
16.6 Alternative Ways of Defining Listener Classes 612
16.7 Case Study: Loan Calculator 615
16.8 Mouse Events 617
16.9 Listener Interface Adapters 620
16.10 Key Events 621
16.11 Animation Using the Timer Class 625
Chapter 17 GUI Components 639
17.1 Introduction 640
17.2 Events for JCheckBox, JRadioButton and JTextField 640
17.3 Text Areas 644
17.4 Combo Boxes 647

17.5 Lists 650
17.6 Scroll Bars 654
17.7 Sliders 657
17.8 Creating Multiple Windows 660
Chapter 18 Applets and Multimedia 671
18.1 Introduction 672
18.2 Developing Applets 672
18.3 The HTML File and the
<applet>Tag 673
18.4 Applet Security Restrictions 675
xxii Contents
18.5 Enabling Applets to Run as Applications 676
18.6 Applet Life-Cycle Methods 677
18.7 Passing Strings to Applets 679
18.8 Case Study: Bouncing Ball 683
18.9 Case Study: Developing a Tic-Tac-Toe Game 686
18.10 Locating Resources Using the
URL Class 691
18.11 Playing Audio in Any Java Program 693
18.12 Case Study: National Flags and Anthems 695
Chapter 19 Binary I/O 709
19.1 Introduction 710
19.2 How Is Text I/O Handled in Java? 710
19.3 Text I/O vs. Binary I/O 711
19.4 Binary I/O Classes 712
19.5 Case Study: Copying Files 722
19.6 Object I/O 724
19.7 Random-Access Files 729
Chapter 20 Recursion 737
20.1 Introduction 738

20.2 Case Study: Computing Factorials 738
20.3 Case Study: Computing Fibonacci Numbers 741
20.4 Problem Solving Using Recursion 744
20.5 Recursive Helper Methods 746
20.6 Case Study: Finding the Directory Size 749
20.7 Case Study: Towers of Hanoi 750
20.8 Case Study: Fractals 754
20.9 Recursion vs. Iteration 757
20.10 Tail Recursion 758
Chapter 21 Generics 769
21.1 Introduction 770
21.2 Motivations and Benefits 770
21.3 Defining Generic Classes and Interfaces 772
21.4 Generic Methods 774
21.5 Case Study: Sorting an Array of Objects 776
21.6 Raw Types and Backward Compatibility 778
21.7 Wildcard Generic Types 779
21.8 Erasure and Restrictions on Generics 782
21.9 Case Study: Generic Matrix Class 784
Contents xxiii
Chapter 22 Lists, Stacks, Queues, and
Priority Queues
793
22.1 Introduction 794
22.2 Collections 794
22.3 Iterators 798
22.4 Lists 799
22.5 The Comparator Interface 803
22.6 Static Methods for Lists and Collections 805
22.7 Case Study: Bouncing Balls 809

22.8 The Vector and Stack Classes 813
22.9 Queues and Priority Queues 814
22.10 Case Study: Evaluating Expressions 817
Chapter 23 Sets and Maps 829
23.1 Introduction 830
23.2 Sets 830
23.3 Comparing the Performance of Sets and Lists 838
23.4 Case Study: Counting Keywords 841
23.5 Maps 842
23.6 Case Study: Occurrences of Words 847
23.7 Singleton and Unmodifiable Collections and Maps 848
Chapter 24 Developing Efficient Algorithms 853
24.1 Introduction 854
24.2 Measuring Algorithm Efficiency Using Big O Notation 854
24.3 Examples: Determining Big O 856
24.4 Analyzing Algorithm Time Complexity 859
24.5 Finding Fibonacci Numbers Using Dynamic Programming 862
24.6 Finding Greatest Common Divisors Using Euclid’s Algorithm 864
24.7 Efficient Algorithms for Finding Prime Numbers 869
24.8 Finding the Closest Pair of Points Using Divide-and-Conquer 875
24.9 Solving the Eight Queens Problem Using Backtracking 877
24.10 Computational Geometry: Finding a Convex Hull 880
Chapter 25 Sorting 893
25.1 Introduction 894
25.2 Bubble Sort 894
25.3 Merge Sort 896
25.4 Quick Sort 900
25.5 Heap Sort 904
25.6 Bucket Sort and Radix Sort 911
25.7 External Sort 913

xxiv Contents

×