Tải bản đầy đủ (.pdf) (853 trang)

Wiley java concepts 6th edition compatible with java 5 6 and 7

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 (27.8 MB, 853 trang )



This online teaching and learning environment
integrates the entire digital textbook with the
most effective instructor and student resources
WRÀWHYHU\OHDUQLQJVW\OH

With WileyPLUS:
‡ Students achieve concept
mastery in a rich,
structured environment
that’s available 24/7

‡ Instructors personalize and manage
their course more effectively with
assessment, assignments, grade
tracking, and more

‡ manage time better
‡study smarter
‡ save money

From multiple study paths, to self-assessment, to a wealth of interactive
visual and audio resources, WileyPLUS gives you everything you need to
personalize the teaching and learning experience.

» F i n d o u t h ow t o M A K E I T YO U R S »
www.wileyplus.com


ALL THE HELP, RESOURCES, AND PERSONAL SUPPORT


YOU AND YOUR STUDENTS NEED!

2-Minute Tutorials and all
of the resources you & your
students need to get started
www.wileyplus.com/firstday

Student support from an
experienced student user
Ask your local representative
for details!

Collaborate with your colleagues,
find a mentor, attend virtual and live
events, and view resources
www.WhereFacultyConnect.com

Pre-loaded, ready-to-use
assignments and presentations
www.wiley.com/college/quickstart

Technical Support 24/7
FAQs, online chat,
and phone support
www.wileyplus.com/support

Your WileyPLUS
Account Manager
Training and implementation support
www.wileyplus.com/accountmanager


MAKE IT YOURS!


Java

6

th
edition

Concepts


This page intentionally left blank


6

th
edition

Java
Concepts

Cay Horstmann

JOHN WILEY & SONS, INC.

SAN JOSE STATE UNIVERSITY



VICE PRESIDENT AND EXECUTIVE PUBLISHER
EXECUTIVE EDITOR
EDITORIAL ASSISTANT
PRODUCTION SERVICES MANAGER
PRODUCTION EDITOR
EXECUTIVE MARKETING MANAGER
CREATIVE DIRECTOR
SENIOR DESIGNER
PHOTO EDITOR
MEDIA EDITOR
PRODUCTION SERVICES
COVER DESIGNER
COVER ILLUSTRATION

Donald Fowley
Beth Lang Golub
Michael Berlin
Dorothy Sinclair
Janet Foxman
Christopher Ruel
Harry Nolan
Madelyn Lesure
Lisa Gee
Lauren Sapira
Cindy Johnson
Howard Grossman
Susan Cyr


This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson
City. The cover was printed by RRD Jefferson City.
This book is printed on acid-free paper. ∞
Copyright © 2010, 2008, 2006, 2003 John Wiley & Sons, Inc. All rights reserved. No part of this publication
may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc.,
222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street,
Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to
a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return
instructions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside
of the United States, please contact your local representative.
Library of Congress Cataloging-in-Publication Data:
Horstmann, Cay S., 1959Java concepts : compatible with Java 5, 6, and 7 / Cay Horstmann. — 6th ed.
p. cm.
Includes index.
ISBN 978-0-470-50947-0 (pbk.)
1. Java (Computer program language) 2. Electronic data processing. I. Title.
QA76.73.J38H6754 2010
005.13'3--dc22
2009042603
ISBN 978-0-470-50947-0
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1


PREFACE


This book is an introductory text in computer science, focusing on the principles of
programming and software engineering. Here are its key features:
• Teach objects gradually.
In Chapter 2, students learn how to use objects and classes from the standard
library. Chapter 3 shows the mechanics of implementing classes from a given
specification. Students then use simple objects as they master branches, loops, and
arrays. Object-oriented design starts in Chapter 8. This gradual approach allows
students to use objects throughout their study of the core algorithmic topics,
without teaching bad habits that must be un-learned later.
• Reinforce sound engineering practices.
A focus on test-driven development encourages students to test their programs
systematically. A multitude of useful tips on software quality and common errors
encourage the development of good programming habits.
• Help students with guidance and worked examples.
Beginning programmers often ask “How do I start? Now what do I do?” Of
course, an activity as complex as programming cannot be reduced to cookbookstyle instructions. However, step-by-step guidance is immensely helpful for
building confidence and providing an outline for the task at hand. The book contains a large number of “How To” guides for common tasks, with pointers to
additional worked examples on the Web.
• Focus on the essentials while being technically accurate.
An encyclopedic coverage is not helpful for a beginning programmer, but neither
is the opposite—reducing the material to a list of simplistic bullet points that give
an illusion of knowledge. In this book, the essentials of each subject are presented
in digestible chunks, with separate notes that go deeper into good practices or language features when the reader is ready for the additional information.
• Use standard Java.
The book teaches the standard Java language—not a specialized “training
wheels” environment. The Java language, library, and tools are presented at a
depth that is sufficient to solve real-world programming problems.
• Provide an optional graphics track.
Graphical shapes are splendid examples of objects. Many students enjoy writing

programs that create drawings or use graphical user interfaces. If desired, these
topics can be integrated into the course by using the materials at the end of
Chapters 2, 3, 9, and 10.

vii


viii Preface

New in This Edition
This is the fourth edition of Big Java, and the book has once again been carefully
revised and updated. The new and improved features include:

More Help for Beginning Programmers
• The How To sections have been updated and expanded, and four new ones have
been added. Fifteen new Worked Examples (on the companion web site and in
WileyPLUS) walk students through the steps required for solving complex and
interesting problems.
• The treatment of algorithm design, planning, and the use of pseudocode has been
enhanced. Students learn to use pseudocode to define the solution algorithm in
Chapter 1.
• Chapters have been revised to focus each section on a specific learning objective.
These learning objectives also organize the chapter summary to help students
assess their progress.

Annotated Examples
• Syntax diagrams now call out features of typical example code to draw student
attention to the key elements of the syntax. Additional annotations point out
special cases, common errors, and good practice associated with the syntax.
• New example tables clearly present a variety of typical and special cases in a

compact format. Each example is accompanied by a brief note explaining the
usage shown and the values that result from it.
• The gradual introduction of objects has been further improved by providing
additional examples and insights in the early chapters.

Updated for Java 7
• Features introduced in Java 7 are covered as Special Topics so that students can
prepare for them. In this edition, we use Java 5 or 6 for the main discussion.

More Opportunities for Practice
• The test bank has been greatly expanded and improved. (See page xi.)
• A new set of lab assignments enables students to practice solving complex
problems one step at a time.
• The LabRat code evaluation feature, enhanced for this edition, gives students
instant feedback on their programming assignments. (See page xvi.)


Preface ix

A Tour of the Book
The book can be naturally grouped into four parts, as illustrated by Figure 1. The
organization of chapters offers the same flexibility as the previous edition; dependencies among the chapters are also shown in the figure.
Part A: Fundamentals (Chapters 1–7)
Chapter 1 contains a brief introduction to computer science and Java programming.
Chapter 2 shows how to manipulate objects of predefined classes. In Chapter 3,
you will build your own simple classes from given specifications.
Fundamental data types, branches, loops, and arrays are covered in Chapters 4–7.
Part B: Object-Oriented Design (Chapters 8–12)
Chapter 8 takes up the subject of class design in a systematic fashion, and it introduces a very simple subset of the UML notation.
The discussion of polymorphism and inheritance is split into two chapters. Chapter 9 covers interfaces and polymorphism, whereas Chapter 10 covers inheritance.

Introducing interfaces before inheritance pays off in an important way: Students
immediately see polymorphism before getting bogged down with technical details
such as superclass construction.
Exception handling and basic file input/output are covered in Chapter 11. The
exception hierarchy gives a useful example for inheritance.
Chapter 12 contains an introduction to object-oriented design, including two
significant case studies.
Part C: Data Structures and Algorithms (Chapters 13–15)
Chapters 13 through 15 contain an introduction to algorithms and basic data structures, covering recursion, sorting and searching, and linked lists, stacks, and queues.
These topics can be covered as desired after Chapter 7 (see Figure 1).
Recursion is introduced from an object-oriented point of view: An object that
solves a problem recursively constructs another object of the same class that solves
a simpler problem. The idea of having the other object do the simpler job is more
intuitive than having a function call itself.
Chapter 14 covers the fundamental sorting algorithms and gives a gentle introduction to big-Oh analysis. Chapter 15 introduces linked lists, stacks, and queues,
both as abstract data types and as they appear in the standard Java library.
Part D: Advanced Topics (Chapters 16–18)
Chapter 16 covers advanced data structures: hash tables, binary search trees, and
heaps. Chapter 17 introduces Java generics. This chapter is suitable for advanced
students who want to implement their own generic classes and methods. Chapter 18
completes the graphics track coverage of user interfaces with a discussion of layout
management and Swing components. These chapters are available on the Web at
www.wiley.com/college/horstmann , or in the WileyPLUS course for this book.


x

Preface

Fundamentals

Object-Oriented Design
Data Structures & Algorithms
Advanced Topics
1. Introduction
WileyPLUS / Web

2. Using Objects

3. Implementing
Classes

4. Fundamental
Data Types

5. Decisions

6. Iteration
7. Arrrays and
Array Lists
8. Designing
Classes

9. Interfaces and
Polymorphism

10. Inheritance

11. Input/Output
and Exception
Handling


12. ObjectOriented Design

13. Recursion

14. Sorting
and Searching

17. Generic
Programming

15. Intro to
Data Structures

16. Advanced
Data Structures

Figure 1

Chapter Dependencies

18. Graphical
User Interfaces


Preface xi

Appendices
Appendix A lists character escape sequences and the Basic Latin and Latin-1 subsets
of Unicode. Appendices B and C summarize Java reserved words and operators.

Appendix D documents all of the library methods and classes used in this book.
In addition, Appendices E–L are available on the Web and contain quick references on Java syntax, HTML, Java tools, binary numbers, and UML.
Appendix L contains a style guide for use with this book. Many instructors find
it highly beneficial to require a consistent style for all assignments. If this style
guide conflicts with instructor sentiment or local customs, however, it is available in
electronic form so that it can be modified.
Web Resources
This book is complemented by a complete suite of online resources and a robust
WileyPLUS course.
Go to www.wiley.com/college/horstmann to visit the online companion site, which
includes
• Source code for all examples in the book.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Laboratory exercises (and solutions for instructors only).
• Lecture presentation slides (in HTML and PowerPoint formats).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only).
WileyPLUS is an online teaching and learning environment that integrates the
digital textbook with instructor and student resources. See page xvi for details.

Media Resources

Web resources are summarized at
chapter end for easy reference.

Pointers in the book
describe what students
will find on the Web.


• Worked Example How Many Days Have You Been Alive?
• Worked Example Working with Pictures
• Lab Exercises
www.wiley.com/
college/
horstmann

Worked
Example 1.1

Animation Variable Initialization and Assignment
Animation Parameter Passing
Animation Object References
Practice Quiz
Code Completion Exercises

Writing an Algorithm for Tiling a Floor
This Worked Example shows how to develop an algorithm for laying tile in
an alternating pattern of colors.

Special Topic 5.3
Enumeration Types
Special Topic 5.3 introduces enumeration types—types that an hold one of a finite number of
values. An example of an enumeration type is a type FilingStatus with values SINGLE and
MARRIED. This is safer than using integer values, as we did in the TaxReturn class.


xii

Walkthrough


A Walkthrough of the Learning Aids
The pedagogical elements in this book work together to make the book accessible
to beginners as well as those learning Java as a second language.

2.3 The Assignment Operator 39

Throughout each chapter,
margin notes show where
new concepts are introduced
and provide an outline of key ideas.

2.3 The Assignment Operator
You can change the value of a variable with the assignment operator (=). For example, consider the variable declaration

Use the assignment
operator (=) to
change the value
of a variable.

int width = 10;

1

If you want to change the value of the variable, simply assign the new value:
width = 20;

2

The assignment replaces the original value of the variable (see Figure 1).

1

width =

10

2

width =

20

Figure 1

Assigning a New
Value to a Variable

It is an error to use a variable that has never had a value assigned to it. For example, the following assignment statement has an error:
int height;
width = height;

// ERROR—uninitialized variable height

The compiler will complain about an “uninitialized variable” when you use a variable that has never been assigned a value. (See Figure 2.)
Figure 2

Annotated syntax boxes
provide a quick, visual overview
of new language constructs.


An Uninitialized
Variable

height =

Syntax 2.2

No value has been assigned.

Assignment

Syntax

variableName = value;

Example
This is a variable declaration.

Annotations explain
required components
and point to more information
on common errors or best practices
associated with the syntax.

The value of this variable is changed.

double width = 20;
.
.
width = 30;

.
The
.
.
width = width + 10;

This is an assignment statement.

new value of the variable

The same name
can occur on both sides.
See Figure 3.

Summary of Learning Objectives
Explain the flow of execution in a loop.

• A while statement executes a block of code repeatedly. A condition controls for how

long the loop is executed.
• An off-by-one error is a common error when programming loops. Think through

simple test cases to avoid this type of error.
Use for loops to implement counting loops.

• You use a for loop when a variable runs from a starting to an ending value with a

constant increment or decrement.
• Make a choice between symmetric and asymmetric loop bounds.
• Count the number of iterations to check that your for loop is correct.

Implement loops that process a data set until a sentinel value is encountered.

• Sometimes, the termination condition of a loop can only be evaluated in the middle

of a loop. You can introduce a Boolean variable to control such a loop.
Use nested loops to implement multiple levels of iterations.

• When the body of a loop contains another loop, the loops are nested. A typical use

of nested loops is printing a table with rows and columns.

Each section corresponds to a
learning objective, summarized at
chapter end, giving students
a roadmap for assessing what they
know and what they need to review.


Walkthrough xiii

HOW TO 1.1

Developing and Describing an Algorithm

How To guides give step-by-step
guidance for common programming
tasks, emphasizing planning and
testing. They answer the beginner’s
question, “Now what do I do?” and
integrate key concepts into a

problem-solving sequence.

This is the first of many “How To” sections in this book that give you step-by-step procedures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in Java, you need to develop an algorithm—a
method for arriving at a solution for a particular problem. Describe the algorithm in
pseudocode: a sequence of precise steps formulated in English.
For example, consider this problem: You have the choice of buying two cars. One is more
fuel efficient than the other, but also more expensive. You know the price and fuel efficiency
(in miles per gallon, mpg) of both cars. You plan to keep the car for ten years. Assume a price
of $4 per gallon of gas and usage of 15,000 miles per year. You will pay cash for the car and
not worry about financing costs. Which car is the better deal?
Step 1

Determine the inputs and outputs.
In our sample problem, we have these inputs:
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car.
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car.
We simply want to know which car is the better buy. That is the desired output.

Step 2

Break down the problem into smaller tasks.
For each car, we need to know the total cost of driving it. Let’s do this computation separately for each car. Once we have the total cost for each car, we can decide which car is the
better deal.
The total cost for each car is purchase price + operating cost.
We assume a constant usage and gas price for ten years, so the operating cost depends on the
cost of driving the car for one year.
The operating cost is 10 x annual fuel cost.
The annual fuel cost is price per gallon x annual fuel consumed.


The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons.
Step 3

Describe each subtask in pseudocode.
In your description, arrange the steps so that any intermediate values are computed before
they are needed in other computations. For example, list the step
total cost = purchase price + operating cost
after you have computed operating cost.
Here is the algorithm for deciding which car to buy.

Worked Examples apply the steps in
the How To to a different example,
illustrating how they can be used to
plan, implement, and test a solution
to another programming problem.

For each car, compute the total cost as follows:
annual fuel consumed = annual miles driven / fuel efficiency
annual fuel cost = price per gallon x annual fuel consumed
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
If total cost1 < total cost2
Choose car1.
Else
Worked
Writing an Algorithm for Tiling a Floor
Choose car2.
Example 1.1
This Worked Example shows how to develop an algorithm for laying tile in

an alternating pattern of colors.

Worked
Example 6.1

Credit Card Processing
This Worked Example uses a loop to remove spaces from a credit
card number.

180

Decisions

Table 1 Relational Operator Examples

Example tables support beginners
with multiple, concrete examples.
These tables point out common
errors and present another quick
reference to the section’s topic.

Expression

Value

Comment

3 <= 4

true


3 is less than 4; <= tests for “less than or equal”.

3 =< 4

Error

The “less than or equal” operator is <=, not =<,
with the “less than” symbol first.

3 > 4

false

>

4 < 4

false

The left-hand side must be strictly smaller than
the right-hand side.

4 <= 4

true

Both sides are equal;

3 == 5 - 2


true

==

tests for equality.

!=

tests for inequality. It is true that 3 is not 5 – 1.

is the opposite of <=.

<=

tests for “less than or equal”.

3 != 5 - 1

true

3 = 6 / 2

Error

Use == to test for equality.

1.0 / 3.0 == 0.333333333

false


Although the values are very close to one
another, they are not exactly equal. See
Common Error 4.3.

"10" > 5

Error

You cannot compare a string to a number.

"Tomato".substring(0, 3).equals("Tom")

true

Always use the equals method to check whether
two strings have the same contents.

"Tomato".substring(0, 3) == ("Tom")

false

Never use == to compare strings; it only checks
whether the strings are stored in the same
location. See Common Error 5.2 on page 180.

"Tom".equalsIgnoreCase("TOM")

true


Use the equalsIgnoreCase method if you don’t want to
distinguish between uppercase and lowercase letters.


xiv Walkthrough

1 Initialize counter

i =

1

2 Check condition

i =

1

3 Execute loop body

i =

1

4 Update counter

i =

2


Progressive figures trace code
segments to help students visualize
the program flow. Color is used
consistently to make variables and
other elements easily recognizable.

for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}

for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}

for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}

1

for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;

}
2

5 Check condition again

i =

Figure 4

2

box =

for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}

box =

Rectangle
g
x =

5

y =

10


width =

20

height =

30

Rectangle
g

box2 =

x =

5

y =

10

width =

20

height =

30


Execution of a for Loop
3

Students can view animations
of key concepts on the Web.

box =

Rectangle
g

box2 =

x =
y =

Figure 21

Self-check exercises at the
end of each section are designed
to make students think through
the new material—and can
spark discussion in lecture.

SELF CHECK

4.

20
30


Copying Object References

Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
2
3
box2.translate(15, 25);

SELF CHECK

25.
26.

What is the effect of the assignment String greeting2 = greeting?
After calling greeting2.toUpperCase(), what are the contents of greeting and
greeting2?

What is the difference between the following two statements?

public static final double CM_PER_INCH = 2.54;

What is wrong with the following statement sequence?
double diameter = . . .;

double circumference = 3.14 * diameter;
6.2 for Loops
205

ch06/invest2/Investment.java

/**

A class to monitor the growth of an investment that
accumulates interest at a fixed annual rate.
*/
public class Investment
{
private double balance;
private double rate;
private int years;
/**

Constructs an Investment object from a starting balance and
interest rate.
@param aBalance the starting balance
@param aRate the interest rate in percent
*/
public Investment(double aBalance, double aRate)
{
balance = aBalance;
rate = aRate;
years = 0;
}
/**

Keeps accumulating interest until a target balance has
been reached.
@param targetBalance the desired balance
*/


objects (see

Since box and box2 refer to the same rectangle after step 2 , both variables refer to
the moved rectangle after the call to the translate method.
You need not worry too much about the difference between objects and object
references. Much of the time, you will have the correct intuition when you think of
“the object box” rather than the technically more accurate “the object reference
stored in box”. The difference between objects and object references only becomes
apparent when you have multiple variables that refer to the same object.

and

1
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

Rectangle

1

final double CM_PER_INCH = 2.54;

5.

35

width =
height =

Now consider the seemingly analogous code with
Figure 21).
A N I M AT I O N
Object References

20


Program listings are carefully
designed for easy reading,
going well beyond simple
color coding. Methods are set
off by a subtle outline.


Walkthrough xv

Common Error 7.3

Common Errors describe the kinds
of errors that students often make,
with an explanation of why the errors
occur, and what to do about them.

Length and Size
Unfortunately, the Java syntax for determining
the number of elements in an array, an array list,
and a string is not at all consistent. It is a common error to confuse these. You just have to
remember the correct syntax for every data type.

Data Type

Number of Elements

Array

a.length


Array list

a.size()

String

a.length()

;

Quality Tip 4.1
Do Not Use Magic Numbers
A magic number is a numeric constant that appears in your code without explanation. For
example, consider the following scary example that actually occurs in the Java library source:
h = 31 * h + ch;

Why 31? The number of days in January? One less than the number of bits in an integer?
Actually, this code computes a “hash code” from a string—a number that is derived from the
characters in such a way that different strings are likely to yield different hash codes. The
value 31 turns out to scramble the character values nicely.
A better solution is to use a named constant:

Quality Tips explain good
programming practices.
These notes carefully
motivate the reason behind
the advice, and explain why
the effort will be repaid later.


final int HASH_MULTIPLIER = 31;
h = HASH_MULTIPLIER * h + ch;

You should never use magic numbers in your code. Any number that is not completely selfexplanatory should be declared as a named constant. Even the most reasonable cosmic constant is going to change one day. You think there are 365 days in a year? Your customers on
Mars are going to be pretty unhappy about your silly prejudice. Make a constant
final int DAYS_PER_YEAR = 365;

By the way, the device
final int THREE_HUNDRED_AND_SIXTY_FIVE = 365;

Productivity Hint 6.1
Hand-Tracing Loops

Arithmetic Operations
and
In Programming Tip 5.2, you learned about the method of hand tracing. This method is particularly effective for understanding how a loop works.
Consider this example loop. What value is displayed?
int n = 1729;
1 learn how to carry out arithmetic calculations in
In the following sections,
you will
int sum = 0;
Java.
while (n > 0) 2

Productivity Hints teach students how to
use their time and tools more effectively.
They encourage students to be more
productive with tips and techniques
such as hand-tracing.


{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);

3

4

5

6

7

1. There are three variables: n, sum, and digit. The first two variables are initialized with

1729 and 0 before the loop is entered.

n
1729

sum
0

digit


Special Topic 7.2
2. Because n is positive, enter the loop.
3. The variable digit is set to 9 (the remainder of dividing 1729 by 10). The variable sum is
n becomes 172.
(Recall
set to
0 + 9 = 9. syntax
Finally,enhancements
Java 7 introduces several
convenient
for
array that
lists.the remainder in the division 1729 /
is construct
discarded an
because
arguments
arerepeat
integers.).
Cross
out the old
When you declare 10
and
array both
list, you
need not
the type
parameter
in values and
new

ones under the old ones.
the constructor. That write
is, youthe
can
write

ArrayList Syntax Enhancements in Java 7

Special Topics present optional
topics and provide additional
explanation of others. New
features of Java 7 are also
covered in these notes.

ArrayList<String> names = new ArrayList<>();

n
1729
172

instead of

ArrayList<String> names = new ArrayList<String>();

sum
0
9

digit
9


Random Fact 6.1
The First Bug
According to legend, the first bug was one found in 1947 in the Mark II, a huge electromechanical computer at Harvard University. It really was caused by a bug—a moth was
trapped in a relay switch. Actually, from the note that the operator left in the log book next
to the moth (see the figure), it appears as if the term “bug” had already been in active use at
the time.

Random Facts provide historical and
social information on computing—for
interest and to fulfill the “historical and
social context” requirements of the
ACM/IEEE curriculum guidelines.

The First Bug

The pioneering computer scientist Maurice Wilkes wrote: “Somehow, at the Moore
School and afterwards, one had always assumed there would be no particular difficulty in
getting programs right. I can remember the exact instant in time at which it dawned on me


xvi Walkthrough

WileyPLUS
WileyPLUS is an online environment that supports students and instructors. This
book’s WileyPLUS course can complement the printed text or replace it altogether.
For Students

Different learning styles, different levels of proficiency, different levels of preparation—each student is unique. WileyPLUS empowers all students to take advantage
of their individual strengths.

Integrated, multi-media resources—including audio and visual exhibits and demonstration problems—encourage active learning and provide multiple study paths to
fit each student’s learning preferences.
• Worked Examples apply the problem-solving steps in the book to another realistic example.
• Screencast Videos present the author explaining the steps he is taking and showing his work as he solves a programming problem.
• Animations of key concepts allow students to replay dynamic explanations that
instructors usually provide on a whiteboard.
Self-assessments are linked to relevant portions of the text. Students can take control of their own learning and practice until they master the material.
• Practice quizzes can reveal areas where students need to focus.
• Lab exercises can be assigned for self-study or for use in the lab.
• “Code completion” questions enable students to practice programming skills by
filling in small code snippets and getting immediate feedback.
• LabRat provides instant feedback on student solutions to all programming exercises in the book.

For Instructors

WileyPLUS includes all of the instructor resources found on the companion site,
and more.
WileyPLUS gives you tools for identifying those students who are falling behind,
allowing you to intervene accordingly, without having to wait for them to come to
office hours.
• Practice quizzes for pre-reading assessment, self-quizzing, or additional practice
can be used as-is or modified for your course needs.
• Multi-step laboratory exercises can be used in lab or assigned for extra student
practice.
WileyPLUS simplifies and automates student performance assessment, making
assignments, and scoring student work.
• An extensive set of multiple-choice questions for quizzing and testing have been
developed to focus on skills, not just terminology.
• “Code completion” questions can also be added to online quizzes.
• LabRat can track student work on all programming exercises in the book, adding

the student solution and a record of completion to the gradebook.
• Solutions to all review and programming exercises are provided..


Walkthrough xvii

With WileyPLUS …
Students can read the book online
and take advantage of searching
and cross-linking.

Instructors can assign drill-and-practice
questions to check that students did
their reading and grasp basic concepts.

Students can practice programming
by filling in small code snippets
and getting immediate feedback.

Students can play and replay
dynamic explanations of
concepts and program flow.

Students can check that their programming
assignments fulfill the specifications.

To order Java Concepts with its WileyPLUS course for your students, use ISBN 978-0-470-57878-0.


xviii Acknowledgments


Acknowledgments
Many thanks to Beth Golub, Lauren Sapira, Andre Legaspi, Don Fowley, Mike
Berlin, Janet Foxman, Lisa Gee, and Bud Peters at John Wiley & Sons, and Vickie
Piercey at Publishing Services for their help with this project. An especially deep
acknowledgment and thanks goes to Cindy Johnson for her hard work, sound
judgment, and amazing attention to detail.
I am grateful to Suzanne Dietrich, Rick Giles, Kathy Liszka, Stephanie Smullen,
Julius Dichter, Patricia McDermott-Wells, and David Woolbright, for their work
on the supplemental material.
Many thanks to the individuals who reviewed the manuscript for this edition,
made valuable suggestions, and brought an embarrassingly large number of errors
and omissions to my attention. They include:
Ian Barland, Radford University
Rick Birney, Arizona State University
Paul Bladek, Edmonds Community College
Robert P. Burton, Brigham Young University
Teresa Cole, Boise State University
Geoffrey Decker, Northern Illinois University
Eman El-Sheikh, University of West Florida
David Freer, Miami Dade College
Ahmad Ghafarian, North Georgia College & State University
Norman Jacobson, University of California, Irvine
Mugdha Khaladkar, New Jersey Institute of Technology
Hong Lin, University of Houston, Downtown
Jeanna Matthews, Clarkson University
Sandeep R. Mitra, State University of New York, Brockport
Parviz Partow-Navid, California State University, Los Angeles
Jim Perry, Ulster County Community College
Kai Qian, Southern Polytechnic State University

Cyndi Rader, Colorado School of Mines
Chaman Lal Sabharwal, Missouri University of Science and Technology
John Santore, Bridgewater State College
Stephanie Smullen, University of Tennessee, Chattanooga
Monica Sweat, Georgia Institute of Technology
Shannon Tauro, University of California, Irvine
Russell Tessier, University of Massachusetts, Amherst
Jonathan L. Tolstedt, North Dakota State University
David Vineyard, Kettering University
Lea Wittie, Bucknell University


Acknowledgments xix

Every new edition builds on the suggestions and experiences of prior reviewers and
users. I am grateful for the invaluable contributions these individuals have made to
this book:
Tim Andersen, Boise State University
Ivan Bajic, San Diego State University
Ted Bangay, Sheridan Institute of Technology
George Basham, Franklin University
Sambit Bhattacharya, Fayetteville State University
Joseph Bowbeer, Vizrea Corporation
Timothy A. Budd, Oregon State University
Frank Butt, IBM
Jerry Cain, Stanford University
Adam Cannon, Columbia University
Nancy Chase, Gonzaga University
Archana Chidanandan, Rose-Hulman Institute
of Technology

Vincent Cicirello, The Richard Stockton College
of New Jersey
Deborah Coleman, Rochester Institute
of Technology
Valentino Crespi, California State University,
Los Angeles
Jim Cross, Auburn University
Russell Deaton, University of Arkansas
H. E. Dunsmore, Purdue University
Robert Duvall, Duke University
Henry A. Etlinger, Rochester Institute
of Technology
John Fendrich, Bradley University
John Fulton, Franklin University
David Geary, Sabreware, Inc.
Margaret Geroch, Wheeling Jesuit University
Rick Giles, Acadia University
Stacey Grasso, College of San Mateo
Jianchao Han, California State University,
Dominguez Hills
Lisa Hansen, Western New England College
Elliotte Harold
Eileen Head, Binghamton University
Cecily Heiner, University of Utah
Brian Howard, Depauw University
Lubomir Ivanov, Iona College
Curt Jones, Bloomsburg University
Aaron Keen, California Polytechnic State
University, San Luis Obispo


Elliot Koffman, Temple University
Kathy Liszka, University of Akron
Hunter Lloyd, Montana State University
Youmin Lu, Bloomsburg University
John S. Mallozzi, Iona College
John Martin, North Dakota State University
Scott McElfresh, Carnegie Mellon University
Joan McGrory, Christian Brothers University
Carolyn Miller, North Carolina State University
Teng Moh, San Jose State University
John Moore, The Citadel
Faye Navabi, Arizona State University
Kevin O’Gorman, California Polytechnic State
University, San Luis Obispo
Michael Olan, Richard Stockton College
Kevin Parker, Idaho State University
Cornel Pokorny, California Polytechnic State
University, San Luis Obispo
Roger Priebe, University of Texas, Austin
C. Robert Putnam, California State University,
Northridge
Neil Rankin, Worcester Polytechnic Institute
Brad Rippe, Fullerton College
Pedro I. Rivera Vega, University of Puerto Rico,
Mayaguez
Daniel Rogers, SUNY Brockport
Carolyn Schauble, Colorado State University
Christian Shin, SUNY Geneseo
Jeffrey Six, University of Delaware
Don Slater, Carnegie Mellon University

Ken Slonneger, University of Iowa
Peter Stanchev, Kettering University
Ron Taylor, Wright State University
Joseph Vybihal, McGill University
Xiaoming Wei, Iona College
Todd Whittaker, Franklin University
Robert Willhoft, Roberts Wesleyan College
David Womack, University of Texas at
San Antonio
Catherine Wyman, DeVry University
Arthur Yanushka, Christian Brothers University
Salih Yurttas, Texas A&M University


This page intentionally left blank


CONTENTS

PREFACE vii
SPECIAL FEATURES xxviii

CHAPTER 1

1.1
1.2
1.3
1.4
1.5
1.6

1.7
1.8

What Is Programming? 2
The Anatomy of a Computer 3
Translating Human-Readable Programs to Machine Code 7
The Java Programming Language 8
The Structure of a Simple Program 10
Compiling and Running a Java Program 14
Errors 17
Algorithms 19

CHAPTER 2

2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9T
2.10
2.11G
2.12G
2.13G

USING OBJECTS 31


Types 32
Variables 34
The Assignment Operator 37
Objects, Classes, and Methods 39
Method Parameters and Return Values 41
Constructing Objects 44
Accessor and Mutator Methods 46
The API Documentation 47
Implementing a Test Program 50
Object References 52
Graphical Applications and Frame Windows 54
Drawing on a Component 56
Ellipses, Lines, Text, and Color 59

CHAPTER 3

3.1
3.2
3.3
3.4
3.5
3.6T

INTRODUCTION 1

IMPLEMENTING CLASSES 73

Instance Variables 74
Encapsulation 76
Specifying the Public Interface of a Class 77

Commenting the Public Interface 81
Providing the Class Implementation 84
Unit Testing 90

xxi


xxii Contents
3.7 Local Variables 92
3.8 Implicit Parameters 94
3.9G Shape Classes 96
CHAPTER 4

4.1
4.2
4.3
4.4
4.5
4.6

FUNDAMENTAL DATA TYPES 115

Number Types 116
Constants 118
Arithmetic Operations and Mathematical Functions 123
Calling Static Methods 131
Strings 134
Reading Input 138

CHAPTER 5


DECISIONS 151

5.1

The if Statement 152
5.2 Comparing Values 156
5.3 Multiple Alternatives 165
5.4 Using Boolean Expressions 173
5.5T Code Coverage 178
CHAPTER 6

6.1
6.2
6.3
6.4
6.5
6.6T

ITERATION 193

while Loops

194
for Loops 201
Common Loop Algorithms 210
Nested Loops 218
Application: Random Numbers and Simulations 221
Using a Debugger 223


CHAPTER 7

ARRAYS AND ARRAY LISTS 241

7.1
7.2
7.3
7.4

Arrays 242
Array Lists 248
Wrappers and Auto-boxing 254
The Enhanced for Loop 255

7.5
7.6
7.7T
7.8

Partially Filled Arrays 257
Common Array Algorithms 259
Regression Testing 271
Two-Dimensional Arrays 274


Contents xxiii

CHAPTER 8

8.1

8.2
8.3
8.4
8.5
8.6
8.7
8.8
8.9
8.10T

Discovering Classes 290
Cohesion and Coupling 291
Immutable Classes 294
Side Effects 295
Preconditions and Postconditions 299
Static Methods 302
Static Variables 304
Scope 307
Packages 310
Unit Test Frameworks 316

CHAPTER 9

9.1
9.2
9.3
9.4
9.5
9.6T
9.7G

9.8G
9.9G
9.10G
9.11G

INTERFACES AND POLYMORPHISM 329

Using Interfaces for Algorithm Reuse 330
Converting Between Class and Interface Types 336
Polymorphism 338
Using Interfaces for Callbacks 339
Inner Classes 343
Mock Objects 345
Events, Event Sources, and Event Listeners 347
Using Inner Classes for Listeners 350
Building Applications with Buttons 352
Processing Timer Events
Mouse Events

CHAPTER 10

10.1
10.2
10.3
10.4
10.5
10.6
10.7

DESIGNING CLASSES 289


INHERITANCE 367

Inheritance Hierarchies 368
Implementing Subclasses 371
Overriding Methods 375
Subclass Construction 378
Converting Between Subclass and Superclass Types 381
Polymorphism and Inheritance 383
Object: The Cosmic Superclass

391
10.8G Using Inheritance to Customize Frames 397


×