free ebooks ==> www.ebook777.com
This Second Edition of Horstmann’s Java for Everyone provides an introduction to Java programming that
focuses on the essentials and on the problem-solving skills all good programmers need to be successful.
The book is suitable for a first course in programming for computer scientists, engineers, and students in
other technical or scientific disciplines—no prior programming experience is required.
HORSTMANN
AN ACCESSIBLE INTRODUCTION TO THE ESSENTIALS OF JAVA
WITH A PROBLEM-SOLVING EMPHASIS,
IDEAL FOR A FIRST COURSE IN PROGRAMMING
CAY HORSTMANN
KEY FEATURES
JAVA
• Increased coverage of problem-solving: This edition adds practical, step-by-step illustrations
Introduced within the chapters where they are most relevant, these strategies include
Algorithm design (using pseudocode)
Hand-tracing
Stepwise refinement
• New author videos: Video Examples feature Cay Horstmann explaining the steps he is taking and
enhanced with problems from engineering and business domains. Geared to students learning Java
for engineering or business/information systems majors, the exercises are designed to illustrate the
value of programming in those fields.
• New and reorganized topics: All chapters were fully revised and enhanced to respond to user
feedback and improve the flow of topics. The printed book now contains a chapter on Graphical User
Interfaces, and web chapters now include Advanced GUI, Object-Oriented Design, Recursion, Sorting
OBJECTS
• Optional science/engineering and business exercises: End-of-chapter exercises have been
EVERYONE
showing his work as he solves a programming problem
LATE
Storyboards
JAVA F O R
of techniques that will help students devise and evaluate solutions to programming problems.
FOR EVERYONE
late
and Searching, and the Java Collections Framework.. New example tables, photos, and exercises
appear throughout the book.
• Additional programming examples: The author has added many new programming examples and
augmented the source code for the examples in the book with additional program examples.
Technology Officer for Preview Systems, Inc. He is also a consultant for major corporations, universities,
and organizations on Java, C++, Windows, and Internet programming. Horstmann is the author of many
successful professional and academic books, including Big C++, C++ for Everyone, Big Java, and Big Java:
second
Jose State University. He is an experienced professional programmer and was Vice President and Chief
edition
CAY S. HORSTMANN is a Professor of Computer Science in the Department of Computer Science at San
SECOND EDITION
Late Objects—all with John Wiley & Sons, Inc.
COMPATIBLE WITH JAVA 5, 6 & 7
www.wiley.com/college/horstmann
www.ebook777.com
object s
free ebooks ==> www.ebook777.com
free ebooks ==> www.ebook777.com
WileyPLUS is a research-based online environment
for effective teaching and learning.
WileyPLUS builds students’ confidence because it takes the guesswork
out of studying by providing students with a clear roadmap:
• what to do
• how to do it
• if they did it right
It offers interactive resources along with a complete digital textbook that help
students learn more. With WileyPLUS, students take more initiative so you’ll have
greater impact on their achievement in the classroom and beyond.
For more information, visit www.wileyplus.com
www.ebook777.com
free ebooks ==> www.ebook777.com
ALL THE HELP, RESOURCES, AND PERSONAL
SUPPORT YOU AND YOUR STUDENTS NEED!
www.wileyplus.com/resources
2-Minute Tutorials and all
of the resources you and your
students need to get started
Pre-loaded, ready-to-use
assignments and presentations
created by subject matter experts
Student support from an
experienced student user
Collaborate with your colleagues,
find a mentor, attend virtual and live
events, and view resources
www.WhereFacultyConnect.com
Technical Support 24/7
FAQs, online chat,
and phone support
www.wileyplus.com/support
Your WileyPLUS Account Manager,
providing personal training
and support
free ebooks ==> www.ebook777.com
J ava f o r
Everyone
L at e O b j e c t s
www.ebook777.com
free ebooks ==> www.ebook777.com
free ebooks ==> www.ebook777.com
J ava f o r
Everyone
L at e O b j e c t s
Second Edition
Cay Horstmann
San Jose State University
John Wiley & Sons, Inc.
www.ebook777.com
free ebooks ==> www.ebook777.com
VICE PRESIDENT AND EXECUTIVE PUBLISHER
EXECUTIVE EDITOR
CONTENT MANAGER
SENIOR PRODUCTION EDITOR
EXECUTIVE MARKETING MANAGER
CREATIVE DIRECTOR
SENIOR DESIGNER
SENIOR PHOTO EDITOR
PRODUCT Designer
Content Editor
Editorial PROGRAM assistant
Media Specialist
PRODUCTION SERVICES
COVER PHOTO
Don Fowley
Beth Lang Golub
Kevin Holm
John Curley
Christopher Ruel
Harry Nolan
Madelyn Lesure
Lisa Gee
Thomas Kulesa
Wendy Ashenberg
Elizabeth Mills
Lisa Sabatini
Cindy Johnson
© TeeJe/Flickr/Getty Images
This book was set in Stempel Garamond by Publishing Services, and printed and bound by R.R. Donnelley &
Sons Company. The cover was printed by R.R. Donnelley & Sons, Jefferson City.
This book is printed on acid-free paper. ∞
Copyright © 2013, 2010 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.
ISBN 978-1-118-06331-6 (Main Book)
ISBN 978-1-118-12941-8 (Binder-Ready Version)
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
free ebooks ==> www.ebook777.com
P r e fa c e
This book is an introduction to Java and computer programming that focuses on the
essentials—and on effective learning. The book is designed to serve a wide range of
student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior programming experience is required, and only a modest amount of high school algebra is
needed. Here are the key features of this book:
Present fundamentals first.
The book takes a traditional route, first stressing control structures, methods, procedural decomposition, and arrays. Objects are used when appropriate in the early
chapters. Students start designing and implementing their own classes in Chapter 8.
Guidance and worked examples help students succeed.
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 cookbook-style instructions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Additional Worked Examples are available online.
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains
a substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. And additional practice opportunities, including code completion questions, guided lab exercises, and skill-oriented
multiple-choice questions are available online.
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain the
nature and behavior of computer concepts. Step-bystep figures illustrate complex program operations.
Syntax boxes and example tables present a variety
of typical and special cases in a compact format. It
is easy to get the “lay of the land” by browsing the
visuals, before focusing on the textual material.
Focus on the essentials while being
technically accurate.
Visual features help the reader
An encyclopedic coverage is not helpful for a begin- with navigation.
ning programmer, but neither is the opposite—
reducing the material to a list of simplistic bullet points. In this book, the essentials
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.
You will not find artificial over-simplifications that give an illusion of knowledge.
vii
www.ebook777.com
free ebooks ==> www.ebook777.com
viii Preface
New to This Edition
Problem Solving Strategies
This edition adds practical, step-by-step illustrations of techniques that can help students devise and evaluate solutions to programming problems. Introduced where
they are most relevant, these strategies address barriers to success for many students.
Strategies included are:
• Algorithm Design (with pseudocode)
• First Do It By Hand (doing sample
calculations by hand)
• Flowcharts
• Test Cases
• Hand-Tracing
• Storyboards
• Reusable Methods
• Stepwise Refinement
• Adapting Algorithms
• Discovering Algorithms by
Manipulating Physical Objects
• Tracing Objects (identifying state and
behavior)
• Patterns for Object Data
• Thinking Recursively
• Estimating the Running Time of an
Algorithm
Optional Science and Business Exercises
End-of-chapter exercises have been enhanced with problems from scientific and
business domains. Designed to engage students, the exercises illustrate the value of
programming in applied fields.
New and Reorganized Topics
All chapters were revised and enhanced to respond to user feedback and improve the
flow of topics. Loop algorithms are now introduced explicitly in Chapter 4. Debugging is now introduced in a lengthy Video Example in Chapter 5. Additional array
algorithms are presented in Chapter 6 and incorporated into the problem-solving
sections. Input/output is moved up to Chapter 7, but the first two sections may be
used to introduce simple text file processing sooner. New example tables, photos, and
exercises appear throughout the book.
A Tour of the Book
Figure 1 shows the dependencies between the chapters and how topics are organized.
The core material of the book is:
Chapter 1.
Chapter 2.
Chapter 3.
Chapter 4.
Chapter 5.
Chapter 6.
Chapter 7.
Introduction
Fundamental Data Types
Decisions
Loops
Methods
Arrays and Array Lists
Input/Output and Exception Handling
These chapters use a traditional approach. Objects are only used for input/output
and string processing.
free ebooks ==> www.ebook777.com
Preface ix
Three chapters cover object-oriented programming and design:
Objects and Classes
Chapter 9. Inheritance
Chapter 12. Object-Oriented Design
Chapter 8.
(on the Web)
Graphical user interfaces are presented in two chapters:
Chapter 10. Graphical User Interfaces
Chapter 11. Advanced User Interfaces
(on the Web)
The first of these chapters enables students to write programs with buttons, text components, and simple drawings. The second chapter covers layout management and
additional user-interface components.
Fundamentals
1. Introduction
Object-Oriented Design
GUI and Web Programming
Data Structures & Algorithms
Web / WileyPLUS
2. Fundamental
Data Types
3. Decisions
4. Loops
5. Methods
Sections 7.1 and 7.2
(text file processing) can be
covered with Chapter 4.
7. Input/Output
and Exception
Handling
6. Arrays
6. Iteration
and Array Lists
8. Objects and
Classes
9. Inheritance
and Interfaces
10. Graphical
User Interfaces
Figure 1
Chapter
Dependencies
A gentle
introduction to recursion
is optional.
12. ObjectOriented Design
11. Advanced
User Interfaces
www.ebook777.com
13. Recursion
15. The Java
Collections
Framework
14. Sorting
and Searching
free ebooks ==> www.ebook777.com
x Preface
To support a course that goes more deeply into algorithms and data structures, three
additional chapters are available in electronic form on the Web and in WileyPLUS:
Chapter 13. Recursion
Chapter 14. Sorting and Searching
Chapter 15. The Java Collections Framework
Any chapters can be incorporated into a custom print version of this text; ask your
Wiley sales representative for details.
Appendices The first four appendices are in the book; the remainder on the Web.
A.The Basic Latin and Latin-1
Subsets of Unicode
B. Java Operator Summary
C.Java Reserved Word Summary
D.The Java Library
E. Java Syntax Summary
F. HTML Summary
G.Tool Summary
H.Javadoc Summary
I. Number Systems
J. Bit and Shift Operations
K. UML Summary
L. Java Language Coding Guidelines
Many instructors find it highly beneficial to require a consistent style for all assignments. If the style guide in Appendix L 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 sites, which include
• Source code for all examples in the book.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Video Examples in which the author explains the steps he is taking and shows his
work as he solves a programming problem.
• Lab exercises that apply chapter concepts (with solutions for instructors only).
• Lecture presentation slides (in PowerPoint format).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only).
WileyPLUS
WileyPLUS is an online teaching and learning environment that integrates the digital
textbook with instructor and student resources. See pages xv–xvi for details.
VIDEO EXAMPLE 4.2
Pointers in the book
describe what students
will find on the Web.
Drawing a Spiral
In this Video Example, you will see how to develop a program
that draws a spiral.
ONLINE EXAMPLE
A program using
common loop
algorithms.
free ebooks ==> www.ebook777.com
Walkthrough xi
A Walkthrough of the Learning Aids
The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional features, such as chapter objectives and a wealth of exercises, each chapter contains elements geared to today’s visual learner.
4.2 The for Loop 135
4.2 The for Loop
Throughout each chapter,
margin notes show where
new concepts are introduced
and provide an outline of key ideas.
The for loop is
used when a
value runs from a
starting point to an
ending point with a
constant increment
or decrement.
It often happens that you want to execute a sequence of statements a given number
of times. You can use a while loop that is controlled by a counter, as in the following
example:
int counter = 1; // Initialize the counter
while (counter <= 10) // Check the counter
{
System.out.println(counter);
counter++; // Update the counter
}
Because this loop type is so common, there is a special form for it, called the for loop (see Syntax 4.2).
Additional online example code
provides complete programs for
students to run and modify.
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
}
ONLINE EXAMPLE
A program using
common loop
algorithms.
Annotated syntax boxes
provide a quick, visual overview
of new language constructs.
Syntax 4.2
Some people call this loop count-controlled. In contrast, the while loop of the preceding section can be
called an event-controlled loop because it executes
until an event occurs; namely that the balance
reaches the target. Another commonly used term
for a count-controlled loop is definite. You know
from the outset that the loop body will be executed
a definite number of times; ten times in our example. In contrast, you do not know how many iterations it takes to accumulate a target balance. Such a
loop is called indefinite.
for Statement
Syntax
for (initialization;
{
}
Annotations explain required
components and point to more
information on common errors
or best practices associated
with the syntax.
Like a variable in a computer
program, a parking space has
an identifier and a contents.
You can visualize the for loop as
an orderly sequence of steps.
condition; update)
statements
These three
expressions should be related.
See page 163.
This initialization
happens once
before the loop starts.
The variable i is
defined only in this for loop.
See page 161.
The condition is
checked before
each iteration.
for (int i = 5; i <= 10; i++)
{
sum = sum + i;
}
This update is
executed after
each iteration.
This loop executes 6 times.
See page 164.
Analogies to everyday objects are
used to explain the nature and behavior
of concepts such as variables, data
types, loops, and more.
www.ebook777.com
free ebooks ==> www.ebook777.com
xii Walkthrough
Memorable photos reinforce
analogies and help students
remember the concepts.
pie(fruit)
pie(fruit)
A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit” is an example of a parameter variable.
Apples and cherries are examples of arguments.
Problem Solving sections teach
techniques for generating ideas and
evaluating proposed solutions, often
using pencil and paper or other
artifacts. These sections emphasize
that most of the planning and problem
solving that makes students successful
happens away from the computer.
6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects
277
Now how does that help us with our problem, switching the first and the second
half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
Java programmers, we will say that we swap the coins in positions 0 and 4:
Next, we swap the coins in positions 1 and 5:
H O W TO 1 . 1
Describing an Algorithm with Pseudocode
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
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.
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.
WO R K E D E XAMPLE 1. 1
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.
Worked Examples and
Video Examples apply the
steps in the How To to a
different example, showing
how they can be used to
plan, implement, and test
a solution to another
programming problem.
Table 1 Variable Declarations in Java
Variable Name
Comment
int cans = 6;
Declares an integer variable and initializes it with 6.
int total = cans + bottles;
The initial value need not be a constant. (Of course, cans and bottles
must have been previously declared.)
bottles = 1;
Error: The type is missing. This statement is not a declaration but an
int bottles = "10";
Error:
int bottles;
Declares an integer variable without initializing it. This can be a
cause for errors—see Common Error 2.1 on page 37.
int cans, bottles;
Declares two integer variables in a single statement. In this book, we
will declare each variable in a separate statement.
assignment of a new value to an existing variable—see Section 2.1.4.
You cannot initialize a number with a string.
Example tables support beginners
with multiple, concrete examples.
These tables point out common
errors and present another quick
reference to the section’s topic.
free ebooks ==> www.ebook777.com
Walkthrough xiii
Figure 3
Execution of
a for Loop
1 Initialize counter
counter =
1
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
}
1
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
}
2 Check condition
counter =
3 Execute loop body
counter =
1
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 counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
}
1
Method call
result1 =
double result1 = cubeVolume(2);
4 Update counter
counter =
2
sideLength =
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
}
2
Initializing method parameter variable
result1 =
double result1 = cubeVolume(2);
5 Check condition again
counter =
2
sideLength =
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
}
3
About to return to the caller
double volume = sideLength * sideLength * sideLength;
return volume;
4
After method call
2
result1 =
sideLength =
2
volume =
8
result1 =
8
double result1 = cubeVolume(2);
Figure 3 Parameter Passing
Students can view animations
of key concepts on the Web.
A N I M AT I O N
Parameter Passing
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
Write the for loop of the InvestmentTable.java program as a while loop.
How many numbers does this loop print?
6.
7.
for (int n = 10; n >= 0; n--)
{
System.out.println(n);
}
8.
9.
10.
Optional science and business
exercises engage students with
realistic applications of Java.
section_1/DoubleInvestment.java
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
/**
This program computes the time required to double an investment.
*/
public class DoubleInvestment
{
public static void main(String[] args)
{
final double RATE = 5;
final double INITIAL_BALANCE = 10000;
final double TARGET = 2 * INITIAL_BALANCE;
• The parameter variable sideLength of the cubeVolume method is created when the
method is called. 1
• The parameter variable is initialized with the value of the argument that was
passed in the call. In our case, sideLength is set to 2. 2
• The method computes the expression sideLength * sideLength * sideLength, which
has the value 8. That value is stored in the variable volume. 3
• The method returns. All of its variables are removed. The return value is transferred to the caller, that is, the method calling the cubeVolume method. The caller
puts the return value in the result1 variable. 4
Write a for loop that prints all even numbers between 10 and 20 (inclusive).
Write a for loop that computes the sum of the integers from 1 to n.
How would you modify the for loop of the InvestmentTable.java program to
print all balances until the investment has doubled?
Now you can try these exercises at the end of the chapter: R4.3, R4.8, P4.8, P4.13.
•• Science P6.32 Sounds can be represented by an array of “sample
values” that describe the intensity of the sound at a
point in time. The program ch06/sound/SoundEffect.
java reads a sound file (in WAV format), calls a
method process for processing the sample values, and
saves the sound file. Your task is to implement the
process method by introducing an echo. For each
sound value, add the value from 0.2 seconds ago.
theImplement
result so that
no value isAppointment
larger thanand
32767.
•• BusinessScale
P9.21
a superclass
subclasses Onetime, Daily, and Monthly. An appointment has a description (for example, “see the
dentist”) and a date and time. Write a method
occursOn(int year, int month, int day) that checks
whether the appointment occurs on that date.
For example, for a monthly appointment, you
must check whether the day of the month
matches. Then fill an array of Appointment objects
with a mixture of appointments. Have the user enter a date and print out all appointments that occur on that date.
double balance = INITIAL_BALANCE;
int year = 0;
// Count the years required for the investment to double
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
}
System.out.println("The investment doubled after "
+ year + " years.");
Program listings are carefully
designed for easy reading,
going well beyond simple
color coding. Methods are set
off by a subtle outline.
}
}
www.ebook777.com
free ebooks ==> www.ebook777.com
xiv Walkthrough
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.
Common Error 6.4
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.
Programming Tip 3.5
8 public static void main(String[] args)
9 {
10
final double RATE1 = 0.10;
11
final double RATE2 = 0.25;
12
final double RATE1_SINGLE_LIMIT = 32000;
13
final double RATE1_MARRIED_LIMIT = 64000;
14
double tax1 = 0;
15
16
double tax2 = 0;
17
In lines 22 and 25, income and maritalStatus are
initialized by input statements.
20
21
22
23
24
25
Scanner in = new Scanner(System.in);
System.out.print("Please enter your income: ");
double income = in.nextDouble();
a.length
Array list
a.size()
String
a.length()
Hand-tracing helps you
understand whether a
program works correctly.
income
marital
status
tax2
income
marital
status
0
80000
m
tax1
tax2
0
0
tax1
0
System.out.print("Please enter s for single, m for married: ");
String maritalStatus = in.next();
Special Topic 7.2
Special Topics present optional
topics and provide additional
explanation of others. New
features of Java 7 are also
covered in these notes.
Number of Elements
Array
Hand-Tracing
A very useful technique for understanding whether a program works correctly is called hand-tracing. You simulate
the program’s activity on a sheet of paper. You can use this
method with pseudocode or Java code.
Get an index card, a cocktail napkin, or whatever sheet
of paper is within reach. Make a column for each variable.
Have the program code ready. Use a marker, such as a
paper clip, to mark the current statement. In your mind,
execute statements one at a time. Every time the value of a
variable changes, cross out the old value and write the new
value below the old one.
For example, let’s trace the tax program with the data
from the program run on page 102. In lines 15 and 16, tax1 and
tax2 are initialized to 0.
Programming Tips explain
good programming practices,
and encourage students to be
more productive with tips and
techniques such as hand-tracing.
Data Type
File Dialog Boxes
In a program with a graphical user interface, you will want to use a file dialog box (such as the
one shown in the figure below) whenever the users of your program need to pick a file. The
JFileChooser class implements a file dialog box for the Swing user-interface toolkit.
The JFileChooser class has many options to fine-tune the display of the dialog box, but in its
most basic form it is quite simple: Construct a file chooser object; then call the showOpenDialog
or showSaveDialog method. Both methods show the same dialog box, but the button for selecting a file is labeled “Open” or “Save”, depending on which method you call.
For better placement of the dialog box on the screen, you can specify the user-interface
component over which to pop up the dialog box. If you don’t care where the dialog box pops
up, you can simply pass null. The showOpenDialog and showSaveDialog methods return either
JFileChooser.APPROVE_OPTION, if the user has chosen a file, or JFileChooser.CANCEL_OPTION, if the
user canceled the selection. If a file was chosen, then you call the getSelectedFile method to
obtain a File object that describes the file. Here is a complete example:
ONLINE EXAMPLE
A program that
demonstrates how to
use a file chooser.
JFileChooser chooser = new JFileChooser();
Scanner in = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
. . .
}
Call with
showOpenDialog
method
Random Fact 4.1 The First Bug
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.
According to legend,
The pioneering computer scientist
Button is “Save” when
the first bug was Maurice Wilkes wrote, “Somehow, at
showSaveDialog method
found in the Mark II, a huge electrome- the Moore School and afterwards, one
is called
chanical computer at Harvard Univer- had always assumed there would be
sity. It really was caused by a bug—a no particular difficulty in getting promoth was trapped in a relay switch.
A JFileChooser Dialog Box
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.
The First Bug
grams right. I can remember the exact
instant in time at which it dawned on
me that a great part of my future life
would be spent finding mistakes in
my own programs.”
free ebooks ==> www.ebook777.com
Walkthrough xv
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.
• Video Examples 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.
• “Learn by doing” 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.
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.
• Solutions to all review and programming exercises are provided.
To order Java for Everyone, 2e, with its WileyPLUS course for your students, use isbn 978-1-118-28614-2.
www.ebook777.com
free ebooks ==> www.ebook777.com
xvi Walkthrough
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 watch and listen as the author
solves a problem step-by-step.
free ebooks ==> www.ebook777.com
Acknowledgments xvii
Acknowledgments
Many thanks to Beth Lang Golub, Don Fowley, Elizabeth Mills, Thomas Kulesa,
Wendy Ashenberg, Lisa Gee, Andre Legaspi, Kevin Holm, and John Curley 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 Jose Cordova, University of Louisiana, Monroe, Amitava Karmaker, University of Wisconsin, Stout, Khaled Mansour, Washtenaw Community
College, Patricia McDermott-Wells, Florida International University, Brent Seales,
University of Kentucky, Donald Smith, Columbia College, and David Woolbright,
Columbus State University, for their excellent work on the supplemental material. Thank you also to Jose-Arturo Mora-Soto, Jesica Rivero-Espinosa, and JulioAngel Cano-Romero of the University of Madrid for their contribution of business
exercises.
Many thanks to the individuals who provided feedback, reviewed the manuscript,
made valuable suggestions, and brought errors and omissions to my attention. They
include:
Lynn Aaron, SUNY Rockland
Community College
Karen Arlien, Bismarck State College
Jay Asundi, University of Texas, Dallas
Eugene Backlin, DePaul University
William C. Barge, Trine University
Bruce J. Barton, Suffolk County
Community College
Sanjiv K. Bhatia, University of Missouri,
St. Louis
Anna Bieszczad, California State
University, Channel Islands
Jackie Bird, Northwestern University
Eric Bishop, Northland Pioneer College
Paul Bladek, Edmonds Community
College
Paul Logasa Bogen II, Texas A&M
University
Irene Bruno, George Mason University
Paolo Bucci, Ohio State University
Joe Burgin, College of Southern
Maryland
Robert P. Burton, Brigham Young
University
Leonello Calabresi, University of
Maryland University College
Martine Ceberio, University of Texas,
El Paso
Uday Chakraborty, University of
Missouri, St. Louis
Xuemin Chen, Texas Southern
University
Haiyan Cheng, Willamette University
Chakib Chraibi, Barry University
Ta-Tao Chuang, Gonzaga University
Vincent Cicirello, Richard Stockton
College
Mark Clement, Brigham Young
University
Gerald Cohen, St. Joseph’s College
Rebecca Crellin, Community College
of Allegheny County
Leslie Damon, Vermont Technical
College
Geoffrey D. Decker, Northern Illinois
University
Khaled Deeb, Barry University, School
of Adult and Continuing Education
Akshaye Dhawan, Ursinus College
Julius Dichter, University of Bridgeport
Mike Domaratzki, University of
Manitoba
Philip Dorin, Loyola Marymount
University
Anthony J. Dos Reis, SUNY New Paltz
Elizabeth Drake, Santa Fe College
www.ebook777.com
free ebooks ==> www.ebook777.com
xviii Acknowledgments
Tom Duffy, Norwalk Community
College
Michael Eckmann, Skidmore College
Sander Eller, California State
Polytechnic University, Pomona
Amita Engineer, Valencia Community
College
Dave Evans, Pasadena Community
College
James Factor, Alverno College
Chris Fietkiewicz, Case Western
Reserve University
Terrell Foty, Portland Community
College
Valerie Frear, Daytona State College
Ryan Garlick, University of North Texas
Aaron Garrett, Jacksonville State
University
Stephen Gilbert, Orange Coast College
Peter van der Goes, Rose State College
Billie Goldstein, Temple University
Michael Gourley, University of Central
Oklahoma
Grigoriy Grinberg, Montgomery
College
Linwu Gu, Indiana University
Bruce Haft, Glendale Community
College
Nancy Harris, James Madison
University
Allan M. Hart, Minnesota State
University, Mankato
Ric Heishman, George Mason
University
Guy Helmer, Iowa State University
Katherin Herbert, Montclair State
University
Rodney Hoffman, Occidental College
May Hou, Norfolk State University
John Houlihan, Loyola University
Andree Jacobson, University of New
Mexico
Eric Jiang, University of San Diego
Christopher M. Johnson, Guilford
College
Jonathan Kapleau, New Jersey Institute
of Technology
Amitava Karmaker, University of
Wisconsin, Stout
Rajkumar Kempaiah, College of Mount
Saint Vincent
Mugdha Khaladkar, New Jersey
Institute of Technology
Julie King, Sullivan University,
Lexington
Samuel Kohn, Touro College
April Kontostathis, Ursinus College
Ron Krawitz, DeVry University
Debbie Lamprecht, Texas Tech
University
Jian Lin, Eastern Connecticut State
University
Hunter Lloyd, Montana State
University
Cheng Luo, Coppin State University
Kelvin Lwin, University of California,
Merced
Frank Malinowski, Dalton College
John S. Mallozzi, Iona College
Kenneth Martin, University of North
Florida
Deborah Mathews, J. Sargeant
Reynolds Community College
Louis Mazzucco, State University of
New York at Cobleskill and
Excelsior College
Drew McDermott, Yale University
Hugh McGuire, Grand Valley State
University
Michael L. Mick, Purdue University,
Calumet
Jeanne Milostan, University of
California, Merced
Sandeep Mitra, SUNY Brockport
Kenrick Mock, University of Alaska
Anchorage
Namdar Mogharreban, Southern
Illinois University
Shamsi Moussavi, Massbay Community
College
Nannette Napier, Georgia Gwinnett
College
Tony Tuan Nguyen, De Anza College
Michael Ondrasek, Wright State
University
free ebooks ==> www.ebook777.com
Acknowledgments xix
K. Palaniappan, University of Missouri
James Papademas, Oakton Community
College
Gary Parker, Connecticut College
Jody Paul, Metropolitan State College
of Denver
Mark Pendergast, Florida Gulf Coast
University
James T. Pepe, Bentley University
Jeff Pittges, Radford University
Tom Plunkett, Virginia Tech
Linda L. Preece, Southern Illinois
University
Vijay Ramachandran, Colgate
University
Craig Reinhart, California Lutheran
University
Jonathan Robinson, Touro College
Chaman Lal Sabharwal, Missouri
University of Science & Technology
Namita Sarawagi, Rhode Island College
Ben Schafer, University of Northern
Iowa
Walter Schilling, Milwaukee School of
Engineering
Jeffrey Paul Scott, Blackhawk Technical
College
Amon Seagull, NOVA Southeastern
University
Linda Seiter, John Carroll University
Kevin Seppi, Brigham Young University
Ricky J. Sethi, UCLA, USC ISI, and
DeVry University
Ali Shaykhian, Florida Institute of
Technology
Lal Shimpi, Saint Augustine’s College
Victor Shtern, Boston University
Rahul Simha, George Washington
University
Jeff Six, University of Delaware
Donald W. Smith, Columbia College
Peter Spoerri, Fairfield University
David R. Stampf, Suffolk County
Community College
Peter Stanchev, Kettering University
Stu Steiner, Eastern Washington
University
Robert Strader, Stephen F. Austin
State University
David Stucki, Otterbein University
Jeremy Suing, University of Nebraska,
Lincoln
Dave Sullivan, Boston University
Vaidy Sunderam, Emory University
Hong Sung, University of Central
Oklahoma
Monica Sweat, Georgia Tech University
Joseph Szurek, University of Pittsburgh,
Greensburg
Jack Tan, University of Wisconsin
Cynthia Tanner, West Virginia
University
Russell Tessier, University of
Massachusetts, Amherst
Krishnaprasad Thirunarayan, Wright
State University
Megan Thomas, California State
University, Stanislaus
Timothy Urness, Drake University
Eliana Valenzuela-Andrade, University
of Puerto Rico at Arecibo
Tammy VanDeGrift, University of
Portland
Philip Ventura, Broward College
David R. Vineyard, Kettering
University
Qi Wang, Northwest Vista College
Jonathan Weissman, Finger Lakes
Community College
Reginald White, Black Hawk
Community College
Ying Xie, Kennesaw State University
Arthur Yanushka, Christian Brothers
University
Chen Ye, University of Illinois, Chicago
Wook-Sung Yoo, Fairfield University
Bahram Zartoshty, California State
University, Northridge
Frank Zeng, Indiana Wesleyan
University
Hairong Zhao, Purdue University
Calumet
Stephen Zilora, Rochester Institute of
Technology
www.ebook777.com
free ebooks ==> www.ebook777.com
xx Acknowledgments
A special thank you to our class testers for this edition:
Nancy Harris and the students of James Madison University
Mohammed Morovati and the students of College of DuPage
Chris Taylor and the students of Milwaukee School of Engineering
and the first edition:
Michael Ondrasek and the students of Wright State University
Irene Bruno and the students of George Mason University
Cihan Varol and the students of Sam Houston University
David Vineyard and the students of Kettering University
Cindy Tanner and the students of West Virginia University
Andrew Juraszek and the students of J. Sargeant Reynolds Community College
Daisy Sang and the students of California State Polytechnic University, Pomona
Dawn McKinney and the students of University of South Alabama
Nadimpalli Mahadev and the students of Fitchburg State College
Robert Burton and the students of Brigham Young University
Nancy Harris and the students of James Madison University
Tim Weale, Paolo Bucci, and the students of Ohio State University
free ebooks ==> www.ebook777.com
CON T E N T S
Preface vii
Special Features xxvi
Chapter 1
Introduction 1
1.1
Computer Programs 2
1.2
1.3
1.4
1.5
1.6
1.7
The Anatomy of a Computer 3
The Java Programming Language 5
Becoming Familiar with Your Programming Environment 8
Analyzing Your First Program 12
Errors 15
Problem Solving: Algorithm Design 16
Chapter 2
2.1
2.2
2.3
2.4
2.5
Variables 30
Arithmetic 41
Input and Output 48
Problem Solving: First Do It By Hand 57
Strings 59
Chapter 3
3.1
3.2
3.3
3.4
3.5
3.6
3.7
3.8
Decisions 81
The if Statement 82
Comparing Numbers and Strings 88
Multiple Alternatives 96
Nested Branches 100
Problem Solving: Flowcharts 105
Problem Solving: Test Cases 108
Boolean Variables and Operators 111
Application: Input Validation 116
Chapter 4
4.1
4.2
4.3
4.4
Fundamental Data Types 29
Loops 139
The while Loop 140
Problem Solving: Hand-Tracing 147
The for Loop 150
The do Loop 156
xxi
www.ebook777.com
free ebooks ==> www.ebook777.com
xxii Contents
4.5
4.6
4.7
4.8
4.9
Application: Processing Sentinel Values 158
Problem Solving: Storyboards 162
Common Loop Algorithms 165
Nested Loops 172
Application: Random Numbers and Simulations 176
Chapter 5
methods 201
5.1
5.2
Methods as Black Boxes 202
Implementing Methods 204
5.3
5.4
5.5
5.6
5.7
5.8
5.9
Parameter Passing 207
Return Values 210
Methods Without Return Values 214
Problem Solving: Reusable Methods 215
Problem Solving: Stepwise Refinement 218
Variable Scope 225
Recursive Methods (Optional) 228
Chapter 6
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
Arrays 250
The Enhanced for Loop 257
Common Array Algorithms 258
Using Arrays with Methods 268
Problem Solving: Adapting Algorithms 272
Problem Solving: Discovering Algorithms by Manipulating
Physical Objects 279
Two-Dimensional Arrays 282
Array Lists 289
Chapter 7
7.1
7.2
7.3
7.4
7.5
Input/output and exception handling 317
Reading and Writing Text Files 318
Text Input and Output 323
Command Line Arguments 330
Exception Handling 337
Application: Handling Input Errors 347
Chapter 8
8.1
8.2
Arrays and Array lists 249
Objects and Classes 361
Object-Oriented Programming 362
Implementing a Simple Class 364
free ebooks ==> www.ebook777.com
Contents xxiii
8.3
8.4
8.5
8.6
8.7
8.8
8.9
8.10
8.11
Specifying the Public Interface of a Class 367
Designing the Data Representation 371
Implementing Instance Methods 372
Constructors 375
Testing a Class 380
Problem Solving: Tracing Objects 386
Problem Solving: Patterns for Object Data 388
Object References 395
Static Variables and Methods 400
Chapter 9
9.1
9.2
9.3
9.4
9.5
9.6
Inheritance Hierarchies 416
Implementing Subclasses 420
Overriding Methods 424
Polymorphism 430
Object: The Cosmic Superclass 441
Interface Types 448
Chapter 10
10.1
10.2
10.3
10.4
Graphical User Interfaces 465
Frame Windows 466
Events and Event Handling 470
Processing Text Input 481
Creating Drawings 487
Chapter 11
11.1
11.2
11.3
11.4
11.5
11.6
Inheritance and Interfaces 415
Advanced user Interfaces (Web Only)
Layout Management
Choices
Menus
Exploring the Swing Documentation
Using Timer Events for Animations
Mouse Events
Chapter 12
Object-Oriented Design (Web Only)
12.1
Classes and Their Responsibilities
12.2
12.3
12.4
Relationships Between Classes
Application: Printing an Invoice
Packages
Available online in WileyPLUS and at www.wiley.com/college/horstmann.
www.ebook777.com