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

Java TM programming

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 (26.97 MB, 1,947 trang )


get with the programming
Through the power of practice and immediate personalized
feedback, MyProgrammingLab improves your performance.

MyProgrammingLab™
Learn more at www.myprogramminglab.com

ALWAYS LEARNING

PEARSON


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


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.2734.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 countries. 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 permission 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.

10 9 8 7 6 5 4 3 2 1
ISBN 13: 978-0-13-293652-1
ISBN 10: 0-13-293652-6


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 students 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 programming, GUI programming, algorithms and data structures, concurrency, networking, internationalization, 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.

what is new?


problem-driven

fundamentals-first

comprehensive version

brief version

examples and exercises

Sincerely,
Y. Daniel Liang

www.cs.armstrong.edu/liang
www.pearsonhighered.com/liang

vii


viii Preface

What’s New in This Edition?
This edition substantially improves Introduction to Java Programming, Eighth Edition. The
major improvements are as follows:
complete revision



This edition is completely revised in every detail to enhance clarity, presentation, content,
examples, and exercises.


new problems



New examples and exercises are provided to motivate and stimulate student interest in
programming.

key point



Each section starts with a Key Point that highlights the important concepts covered in the
section.

check point



Check Points provide review questions to help students track their progress and evaluate
their learning after a major concept or example is covered.

test questions



Each chapter provides test questions online. They are grouped by sections for students to
do self-test. The questions are graded online.

VideoNotes




New VideoNotes provide short video tutorials designed to reinforce code.

basic GUI and graphics early



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.

numeric classes covered early



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 earlier



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 generics early



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.

splitting Chapter 22



Chapter 22 is split into two chapters (Chapter 22 and Chapter 23) to make room for incorporating 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.

new JSF chapter



Chapter 44 is completely new to introduce the latest standard on JSF.

new JUnit chapter



Chapter 50 is completely new to introduce testing using JUnit.

developing efficient
algorithms
data structures and algorithm
animation
new data structures materials

parallel programming

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.


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 completing 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 valuable 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 introduction to Java programming, data structures and algorithms, and database and Web programming. Because knowledge is cumulative, the early chapters provide the conceptual basis


x Preface

Part I: Fundamentals of
Programming

Part III: GUI Programming

Part II: Object-Oriented
Programming

Part IV: Data Structures and
Algorithms

Chapter 8 Objects and Classes

Chapter 12 GUI Basics

Ch 6

Chapter 20 Recursion


Chapter 9 Strings

Chapter 13 Graphics

Ch 15

Chapter 21 Generics

Chapter 2 Elementary
Programming

Chapter 10 Thinking in Objects

Chapter 16 Event-Driven
Programming

Chapter 22 Lists, Stacks, Queues,
and Priority Queues

Chapter 3 Selections

Chapter 11 Inheritance and
Polymorphism

Chapter 17 GUI Components

Chapter 23 Sets and Maps

Chapter 1 Introduction to
Computers, Programs, and

Java

Ch 18

Part V: Advanced Java
Programming
Chapter 32 Multithreading and
Parallel Programming
Chapter 33 Networking
Chapter 34 Java Database
Programming
Chapter 35 Internationalization

Chapter 4 Loops

Chapter 14 Exception
Handling and Text I/O

Chapter 18 Applets and
Multimedia

Chapter 24 Developping
Efficient Algorithms

Chapter 15 Abstract Classes
and Interfaces

Chapter 36 JavaBeans and Bean
Events


Chapter 25 Sorting

Chapter 5 Methods
Chapter 6 Single-Dimensional
Arrays

Chapter 19 Binary I/O

Chapter 37 Containers, Layout
Managers, and Borders

Chapter 7 Multidimensional
Arrays

Chapter 38 Menus, Toolbars,
and Dialogs
Note: Chapters 1–20 are in the
brief version of this book.

Chapter 42 Servlets
Chapter 26 Implementing Lists,
Stacks, Queues, and Priority
Queues
Chapter 27 Binary Search Trees
Chapter 28 Hashing

Chapter 39 MVC and Swing
Models

Note: Chapters 1–34 are in the

comprehensive version.

Chapter 29 AVL Trees
Chapter 40 JTable and JTree

Note: Chapters 35–50 are bonus
chapters available from the
Companion Website.

Chapter 49 Java 2D
Ch 8

Chapter 50 Testing Using JUnit

Chapter 41 Advanced
Database Programming

Chapter 30 Graphs and
Applications
Chapter 31 Weighted Graphs and
Applications
Chapter 47 2-4 Trees and BTrees
Chapter 48 Red-Black Trees

Chapter 43 Java Server Pages
Chapter 44 Java Server Faces
Chapter 45 Web Services
Chapter 46 Remote Method
Invocation



Preface xi
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 topics, 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 discussed 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 discusses measuring algorithm efficiency in order to choose an appropriate algorithm for applications. 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 implementing 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 parallel programming. Chapter 33 discusses how to write programs that talk with each other


xii Preface
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 international 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 number 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 supplements on the Companion Website www.cs.armstrong.edu/liang/intro9e.

IDE tutorials

Online Practice and Assessment with
MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming. 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
VideoNote


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.


Preface xiii

LiveLab
This book is accompanied by a complementary Web-based course assessment and management 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 instructors 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


xiv Preface


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 evennumbered 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 editions. 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


Preface xv
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.


BRIEF CONTENTS
1 Introduction to Computers, Programs,
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
xvi

and Java
Elementary Programming
Selections
Loops
Methods
Single-Dimensional Arrays
Multidimensional Arrays
Objects and Classes
Strings

Thinking in Objects
Inheritance and Polymorphism
GUI Basics
Graphics
Exception Handling and Text I/O
Abstract Classes and Interfaces
Event-Driven Programming
GUI Components
Applets and Multimedia
Binary I/O
Recursion
Generics
Lists, Stacks, Queues, and Priority
Queues
Sets and Maps
Developing Efficient Algorithms
Sorting
Implementing Lists, Stacks, Queues,
and Priority Queues
Binary Search Trees
Hashing
AVL Trees
Graphs and Applications
Weighted Graphs and Applications
Multithreading and Parallel
Programming

1
33
81

133
177
223
263
295
335
369
407
445
479
517
559
599
639
671
709
737
769
793
829
853
893
927
961
997
1027
1047
1093
1129


33 Networking
34 Java Database Programming

1175
1211

Chapters 35–50 are bonus Web chapters
35 Internationalization
36 JavaBeans
37 Containers, Layout Managers,
38
39
40
41
42
43
44
45
46
47
48
49
50

and Borders
Menus, Toolbars, and Dialogs
MVC and Swing Models
JTable and JTree
Advanced Database Programming
Servlets

JavaServer Pages
JavaServer Faces
Web Services
Remote Method Invocation
2-4 Trees and B-Trees
Red-Black Trees
Java 2D
Testing Using JUnit

35-1
36-1
37-1
38-1
39-1
40-1
41-1
42-1
43-1
44-1
45-1
46-1
47-1
48-1
49-1
50-1

APPENDIXES
A
B
C

D
E
F
G

Java Keywords
The ASCII Character Set
Operator Precedence Chart
Java Modifiers
Special Floating-Point Values
Number Systems
Bitwise Operatoirns

INDEX

1251
1254
1256
1258
1260
1261
1265

1267


CONTENTS
Chapter 1 Introduction to Computers, Programs,
and Java
1.1

1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11

Introduction
What Is a Computer?
Programming Languages
Operating Systems
Java, the World Wide Web, and Beyond
The Java Language Specification, API, JDK, and IDE
A Simple Java Program
Creating, Compiling, and Executing a Java Program
Displaying Text in a Message Dialog Box
Programming Style and Documentation
Programming Errors

Chapter 2 Elementary Programming
2.1
2.2
2.3
2.4
2.5
2.6

2.7
2.8
2.9
2.10
2.11
2.12
2.13
2.14
2.15
2.16
2.17
2.18
2.19

Introduction
Writing a Simple Program
Reading Input from the Console
Identifiers
Variables
Assignment Statements and Assignment Expressions
Named Constants
Naming Conventions
Numeric Data Types and Operations
Numeric Literals
Evaluating Expressions and Operator Precedence
Case Study: Displaying the Current Time
Augmented Assignment Operators
Increment and Decrement Operators
Numeric Type Conversions
Software Development Process

Character Data Type and Operations
The String Type
Getting Input from Input Dialogs

Chapter 3 Selections
3.1
3.2

Introduction
boolean Data Type

1
2
2
9
12
13
16
16
19
22
24
26
33
34
34
37
40
40
42

43
44
44
48
50
51
53
54
56
58
62
68
70
81
82
82

xvii


xviii Contents
3.3
3.4
3.5
3.6
3.7
3.8
3.9
3.10
3.11

3.12
3.13
3.14
3.15
3.16
3.17
3.18
3.19

if Statements

Case Study: Guessing Birthdays
Two-Way if-else Statements
Nested if and Multi-Way if-else Statements
Common Errors in Selection Statements
Generating Random Numbers
Case Study: Computing Body Mass Index
Case Study: Computing Taxes
Logical Operators
Case Study: Determining Leap Year
Case Study: Lottery
switch Statements
Conditional Expressions
Formatting Console Output
Operator Precedence and Associativity
Confirmation Dialogs
Debugging

84
86

89
91
93
96
97
99
101
105
106
108
111
112
115
117
119

Chapter 4 Loops

133

4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
4.10

4.11

134
134
144
146
150
152
154
155
159
162
164

Introduction
The while Loop
The do-while Loop
The for Loop
Which Loop to Use?
Nested Loops
Minimizing Numeric Errors
Case Studies
Keywords break and continue
Case Study: Displaying Prime Numbers
Controlling a Loop with a Confirmation Dialog

Chapter 5 Methods
5.1
5.2
5.3

5.4
5.5
5.6
5.7
5.8
5.9
5.10

177

Introduction
Defining a Method
Calling a Method

178
178
180

void Method Example

183
186
189
191
193
196

Passing Parameters by Values
Modularizing Code
Case Study: Converting Decimals to Hexadecimals

Overloading Methods
The Scope of Variables
The Math Class

197


Contents xix
5.11
5.12

Case Study: Generating Random Characters
Method Abstraction and Stepwise Refinement

Chapter 6 Single-Dimensional Arrays
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9
6.10
6.11
6.12

Introduction
Array Basics

Case Study: Lotto Numbers
Case Study: Deck of Cards
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
Case Study: Counting the Occurrences of Each Letter
Variable-Length Argument Lists
Searching Arrays
Sorting Arrays
The Arrays Class

Chapter 7 Multidimensional Arrays
7.1
7.2
7.3
7.4
7.5
7.6
7.7
7.8

Introduction
Two-Dimensional Array Basics
Processing Two-Dimensional Arrays
Passing Two-Dimensional Arrays to Methods
Case Study: Grading a Multiple-Choice Test
Case Study: Finding the Closest Pair
Case Study: Sudoku
Multidimensional Arrays


Chapter 8 Objects and Classes
8.1
8.2
8.3
8.4
8.5
8.6
8.7
8.8
8.9
8.10
8.11

Introduction
Defining Classes for Objects
Example: Defining Classes and Creating Objects
Constructing Objects Using Constructors
Accessing Objects via Reference Variables
Using Classes from the Java Library
Static Variables, Constants, and Methods
Visibility Modifiers
Data Field Encapsulation
Passing Objects to Methods
Array of Objects

Chapter 9 Strings
9.1
9.2

Introduction

The String Class

201
203
223
224
224
231
234
236
237
240
241
244
245
248
252
263
264
264
267
269
270
272
274
277
295
296
296
298

303
304
308
312
317
319
322
326
335
336
336


xx Contents
9.3
9.4
9.5
9.6

Case Study: Checking Palindromes
Case Study: Converting Hexadecimals to Decimals
The Character Class
The StringBuilder and StringBuffer

9.7

Command-Line Arguments

Chapter 10 Thinking in Objects
10.1

10.2
10.3
10.4
10.5
10.6
10.7
10.8
10.9
10.10
10.11
10.12
10.13
10.14

Introduction
Immutable Objects and Classes
The Scope of Variables
The this Reference
Class Abstraction and Encapsulation
Object-Oriented Thinking
Object Composition
Case Study: Designing the Course Class
Case Study: Designing a Class for Stacks
Case Study: Designing the GuessDate Class
Class Design Guidelines
Processing Primitive Data Type Values as Objects
Automatic Conversion between Primitive Types
and Wrapper Class Types
The BigInteger and BigDecimal


Chapter 11 Inheritance and Polymorphism
11.1
11.2
11.3
11.4
11.5
11.6
11.7
11.8
11.9
11.10
11.11
11.12
11.13

Introduction
Superclasses and Subclasses
Using the super Keyword
Overriding Methods
Overriding vs. Overloading
The Object Class and Its toString()
Polymorphism
Dynamic Binding
Casting Objects and the instanceof Operator
The Object’s equals method
The ArrayList Class
Case Study: A Custom Stack Class
The protected Data and Methods

11.14


Preventing Extending and Overriding

Chapter 12 GUI Basics
12.1
12.2

Introduction
Swing vs. AWT

347
348
350
353
358
369
370
370
371
373
375
379
382
384
386
388
391
393
396
397

407
408
408
414
418
418
420
421
422
425
429
430
436
437
439
445
446
446


Contents xxi
12.3
12.4
12.5
12.6
12.7
12.8
12.9
12.10
12.11

12.12
12.13
12.14
12.15

The Java GUI API
Frames
Layout Managers
Using Panels as Subcontainers
The Color Class
The Font Class
Common Features of Swing GUI Components
Image Icons
JButton
JCheckBox
JRadioButton

Labels
Text Fields

Chapter 13 Graphics
13.1
13.2
13.3
13.4
13.5
13.6
13.7
13.8
13.9

13.10
13.11

Introduction
The Graphics Class
Drawing Strings, Lines, Rectangles, and Ovals
Case Study: The FigurePanel Class
Drawing Arcs
Drawing Polygons and Polylines
Centering a String Using the FontMetrics Class
Case Study: The MessagePanel Class
Case Study: The StillClock Class
Displaying Images
Case Study: The ImageViewer Class

Chapter 14 Exception Handling and Text I/O
14.1
14.2
14.3
14.4
14.5
14.6
14.7
14.8
14.9
14.10

Introduction
Exception-Handling Overview
Exception Types

More on Exception Handling
The finally Clause
When to Use Exceptions
Rethrowing Exceptions
Chained Exceptions
Defining Custom Exception Classes
The File Class

14.11
14.12
14.13

File Input and Output
File Dialogs
Reading Data from the Web

446
449
451
458
460
461
462
465
467
471
472
473
474


479
480
480
483
485
488
490
493
495
500
504
506

517
518
518
523
526
534
535
536
537
538
541
544
549
551


xxii Contents


Chapter 15 Abstract Classes and Interfaces

559

15.1
15.2

Introduction
Abstract Classes

560
560

15.3
15.4
15.5
15.6
15.7

Case Study: the Abstract Number Class
Case Study: Calendar and GregorianCalendar
Interfaces
The Comparable Interface
The Cloneable Interface

565
567
570
573

577

15.8
15.9

Interfaces vs. Abstract Classes
Case Study: The Rational Class

581
584

Chapter 16 Event-Driven Programming

599

16.1
16.2

Introduction
Events and Event Sources

600
602

16.3
16.4

Listeners, Registrations, and Handling Events
Inner Classes


603
608

16.5
16.6
16.7

Anonymous Class Listeners
Alternative Ways of Defining Listener Classes
Case Study: Loan Calculator

609
612
615

Mouse Events
Listener Interface Adapters
Key Events
Animation Using the Timer Class

617
620
621
625

16.8
16.9
16.10
16.11


Chapter 17 GUI Components

639

17.1
17.2
17.3
17.4
17.5

Introduction
Events for JCheckBox, JRadioButton and JTextField
Text Areas
Combo Boxes
Lists

640
640
644
647
650

17.6
17.7
17.8

Scroll Bars
Sliders
Creating Multiple Windows


654
657
660

Chapter 18 Applets and Multimedia

671

18.1
18.2

Introduction
Developing Applets

672
672

18.3
18.4

The HTML File and the <applet>Tag
Applet Security Restrictions

673
675


Contents xxiii
18.5
18.6

18.7
18.8
18.9
18.10

Enabling Applets to Run as Applications
Applet Life-Cycle Methods
Passing Strings to Applets
Case Study: Bouncing Ball
Case Study: Developing a Tic-Tac-Toe Game
Locating Resources Using the URL Class

18.11
18.12

Playing Audio in Any Java Program
Case Study: National Flags and Anthems

Chapter 19 Binary I/O
19.1
19.2
19.3
19.4
19.5
19.6
19.7

Introduction
How Is Text I/O Handled in Java?
Text I/O vs. Binary I/O

Binary I/O Classes
Case Study: Copying Files
Object I/O
Random-Access Files

Chapter 20 Recursion
20.1
20.2
20.3
20.4
20.5
20.6
20.7
20.8
20.9
20.10

Introduction
Case Study: Computing Factorials
Case Study: Computing Fibonacci Numbers
Problem Solving Using Recursion
Recursive Helper Methods
Case Study: Finding the Directory Size
Case Study: Towers of Hanoi
Case Study: Fractals
Recursion vs. Iteration
Tail Recursion

Chapter 21 Generics
21.1

21.2
21.3
21.4
21.5
21.6
21.7
21.8
21.9

Introduction
Motivations and Benefits
Defining Generic Classes and Interfaces
Generic Methods
Case Study: Sorting an Array of Objects
Raw Types and Backward Compatibility
Wildcard Generic Types
Erasure and Restrictions on Generics
Case Study: Generic Matrix Class

676
677
679
683
686
691
693
695

709
710

710
711
712
722
724
729

737
738
738
741
744
746
749
750
754
757
758

769
770
770
772
774
776
778
779
782
784



xxiv Contents

Chapter 22 Lists, Stacks, Queues, and
Priority Queues

793

22.1
22.2
22.3
22.4

Introduction
Collections
Iterators
Lists

794
794
798
799

22.5

The Comparator Interface

22.6
22.7
22.8

22.9

Static Methods for Lists and Collections
Case Study: Bouncing Balls
The Vector and Stack Classes
Queues and Priority Queues

803
805
809
813
814

Case Study: Evaluating Expressions

817

22.10

Chapter 23 Sets and Maps

829

23.1
23.2

Introduction
Sets

830

830

23.3
23.4
23.5
23.6
23.7

Comparing the Performance of Sets and Lists
Case Study: Counting Keywords
Maps
Case Study: Occurrences of Words
Singleton and Unmodifiable Collections and Maps

838
841
842
847
848

Chapter 24 Developing Efficient Algorithms

853

24.1
24.2
24.3
24.4
24.5
24.6

24.7
24.8
24.9
24.10

Introduction
Measuring Algorithm Efficiency Using Big O Notation
Examples: Determining Big O
Analyzing Algorithm Time Complexity
Finding Fibonacci Numbers Using Dynamic Programming
Finding Greatest Common Divisors Using Euclid’s Algorithm
Efficient Algorithms for Finding Prime Numbers
Finding the Closest Pair of Points Using Divide-and-Conquer
Solving the Eight Queens Problem Using Backtracking
Computational Geometry: Finding a Convex Hull

Chapter 25 Sorting

854
854
856
859
862
864
869
875
877
880
893


25.1

Introduction

894

25.2
25.3

Bubble Sort
Merge Sort

894
896

25.4
25.5

Quick Sort
Heap Sort

900
904

25.6
25.7

Bucket Sort and Radix Sort
External Sort


911
913


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×