100% found this document useful (6 votes)
15 views

Complete Download (Ebook PDF) Big Java: Early Objects 5th Edition PDF All Chapters

Objects

Uploaded by

betkafagiry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
15 views

Complete Download (Ebook PDF) Big Java: Early Objects 5th Edition PDF All Chapters

Objects

Uploaded by

betkafagiry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Download the full version of the ebook now at ebooksecure.

com

(eBook PDF) Big Java: Early Objects 5th


Edition

https://ebooksecure.com/product/ebook-pdf-big-
java-early-objects-5th-edition/

Explore and download more ebook at https://ebooksecure.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

(eBook PDF) Big Java: Early Objects, 7th Edition

https://ebooksecure.com/product/ebook-pdf-big-java-early-objects-7th-
edition/

ebooksecure.com

(eBook PDF) Big Java: Early Objects, 6th Edition by Cay S.


Horstmann

https://ebooksecure.com/product/ebook-pdf-big-java-early-objects-6th-
edition-by-cay-s-horstmann/

ebooksecure.com

(eBook PDF) Starting Out with Java: Early Objects 5th


Edition

https://ebooksecure.com/product/ebook-pdf-starting-out-with-java-
early-objects-5th-edition/

ebooksecure.com

(eBook PDF) Corporate Finance 4th Edition by Jonathan Berk

https://ebooksecure.com/product/ebook-pdf-corporate-finance-4th-
edition-by-jonathan-berk/

ebooksecure.com
(eBook PDF) Liberty, Equality, Power: A History of the
American People 7th Edition

https://ebooksecure.com/product/ebook-pdf-liberty-equality-power-a-
history-of-the-american-people-7th-edition/

ebooksecure.com

(eBook PDF) America: A Concise History, Volume 2 Sixth


Edition

https://ebooksecure.com/product/ebook-pdf-america-a-concise-history-
volume-2-sixth-edition/

ebooksecure.com

Cultivating an understanding of curiosity as a seed for


creativity - eBook PDF

https://ebooksecure.com/download/cultivating-an-understanding-of-
curiosity-as-a-seed-for-creativity-ebook-pdf/

ebooksecure.com

(eBook PDF) Medical Assisting: Administrative Procedures


7th Edition

https://ebooksecure.com/product/ebook-pdf-medical-assisting-
administrative-procedures-7th-edition/

ebooksecure.com

Advanced Clinical Naturopathic Medicine 1st Edition -


eBook PDF

https://ebooksecure.com/download/advanced-clinical-naturopathic-
medicine-ebook-pdf/

ebooksecure.com
(eBook PDF) BUSN 3rd Canadian Edition by
Kelly,Mackenzie,Snow

https://ebooksecure.com/product/ebook-pdf-busn-3rd-canadian-edition-
by-kellymackenziesnow/

ebooksecure.com
vi Preface

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 intro-
duces a very simple subset of the UML notation. The discussion of polymorphism
and inheritance is split into two chapters. Chapter 9 covers inheritance and polymor-
phism, whereas Chapter 10 covers interfaces. 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–18)


Chapters 13 through 18 contain an introduction to algorithms and data structures,
covering recursion, sorting and searching, linked lists, binary trees, and hash tables.
These topics may be outside the scope of a one-semester course, but can be covered
as desired after Chapter 7 (see Figure 1). Recursion, in Chapter 13, starts with simple
examples and progresses to meaningful applications that would be difficult to imple-
ment iteratively. Chapter 14 covers quadratic sorting algorithms as well as merge sort,
with an informal introduction to big-Oh notation. Each data structure is presented
in the context of the standard Java collections library. You will learn the essential
abstractions of the standard library (such as iterators, sets, and maps) as well as the
performance characteristics of the various collections. Chapter 18 introduces Java
generics. This chapter is suitable for advanced students who want to implement their
own generic classes and methods.

Part D: Applied Topics (Chapters 19–25)


Chapters 19 through 25 cover Java programming techniques that definitely go
beyond a first course in Java (21–25 are on the book’s companion site). Although, as
already mentioned, a comprehensive coverage of the Java library would span many
volumes, many instructors prefer that a textbook should give students additional
reference material valuable beyond their first course. Some institutions also teach a
second-semester course that covers more practical programming aspects such as data-
base and network programming, rather than the more traditional in-depth material
on data structures and algorithms. This book can be used in a two-semester course
to give students an introduction to programming fundamentals and broad coverage
of applications. Alternatively, the material in the final chapters can be useful for stu-
dent projects. The applied topics include graphical user-interface design, advanced
file handling, multithreading, and those technologies that are of particular interest to
server-side programming: networking, databases, XML, and web applications. The
Internet has made it possible to deploy many useful applications on servers, often
accessed by nothing more than a browser. This server-centric approach to application
development was in part made possible by the Java language and libraries, and today,
much of the industrial use of Java is in server-side programming.

bj5_fm_06.indd 6 11/6/12 9:18 PM


Preface vii

Appendices
Many instructors find it highly beneficial to require a consistent style for all assign-
ments. If the style guide in Appendix I conflicts with instructor sentiment or local
customs, however, it is available in electronic form so that it can be modified.
A. The Basic Latin and Latin-1 Subsets F. Tool Summary
of Unicode G. Number Systems
B. Java Operator Summary H. UML Summary
C. Java Reserved Word Summary I. Java Language Coding Guidelines
D. The Java Library J. HTML Summary
E. Java Syntax Summary

Custom Book and eBook Options


Big Java may be ordered as a custom print or eBook that includes your choice of
chapters—including those from other Horstmann titles. Visit customselect.wiley.com
to create your custom book order.
To order the Wiley Select Edition of Big Java with all 25 chapters in the printed
book, specify ISBN 978-1-119-93670-1 when you order books.
Big Java is available in a variety of eBook formats at prices that are significantly
lower than the printed book. Please contact your Wiley sales rep for more informa-
tion or check www.wiley.com/college/horstmann for available versions.

Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/college/horstmann to visit the online companion sites, which include

• “CodeCheck,” a new online service currently in development by Cay Horstmann


that students can use to check their homework assignments and to work on addi-
tional practice problems. Visit http://horstmann.com/codecheck to learn more and to
try it out.
• Source code for all example programs in the book and in online examples.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Animations of key concepts.
• Lab exercises that apply chapter concepts (with solutions for instructors only).
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.

WORKED EXAMPLE 6.3 A Sample Debugging Session


Learn how to find bugs in an algorithm for counting the
Pointers in the book syllables of a word. Go to wiley.com/go/javaexamples and
download Worked Example 6.3.
describe what students
will find on the Web.
FULL CODE EXAMPLE

Go to wiley.com/go/
javacode to download
a program that dem-
onstrates variables
and assignments.

bj5_fm_06.indd 7 10/26/12 11:44 AM


viii Walkthrough

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.

254 Chapter 6 Loops

6.3 The for Loop


Throughout each chapter,
It often happens that you want to execute a sequence of statements a given number
margin notes show where The for loop is
used when a of times. You can use a while loop that is controlled by a counter, as in the following
example:
new concepts are introduced
value runs from a
starting point to an
ending point with a int counter = 1; // Initialize the counter
and provide an outline of key ideas. constant increment
or decrement.
while (counter <= 10) // Check the counter
{
System.out.println(counter);
counter++; // Update the counter
}

Because this loop type is so common, there is a spe-


cial form for it, called the for loop (see Syntax 6.2).
for (int counter = 1; counter <= 10; counter++)
{
Additional full code examples }
System.out.println(counter);

provides complete programs for FULL CODE EXAMPLE Some people call this loop count-controlled. In con-
trast, the while loop of the preceding section can be
students to run and modify.
Go to wiley.com/go/
javacode to download
a program that
called an event-controlled loop because it executes
uses common loop until an event occurs; namely that the balance reaches
algorithms. 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
Annotated syntax boxes called indefinite. You can visualize the for loop as
an orderly sequence of steps.
provide a quick, visual overview
of new language constructs. Syntax 6.2 for Statement

Syntax for (initialization; condition; update)


{
statements
}
These three
expressions should be related.
See page 259.

Annotations explain required This initialization The condition is This update is


components and point to more happens once
before the loop starts.
checked before
each iteration.
executed after
each iteration.
information on common errors for (int i = 5; i <= 10; i++)
or best practices associated The variable i is
{
sum = sum + i; This loop executes 6 times.
with the syntax. defined only in this for loop.
See page 261.
} See page 260.

Analogies to everyday objects are


used to explain the nature and behavior
of concepts such as variables, data
Like a variable in a computer types, loops, and more.
program, a parking space has
an identifier and a contents.

bj5_fm_06.indd 8 10/24/12 6:23 PM


Walkthrough ix

Memorable photos reinforce


analogies and help students
remember the concepts.

In the same way that there can be a street named “Main Street” in different cities,
a Java program can have multiple variables with the same name.

Problem Solving sections teach


techniques for generating ideas and 7.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 339

evaluating proposed solutions, often Now how does that help us with our problem, switching the first and the second
using pencil and paper or other half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
artifacts. These sections emphasize Java programmers, we will say that we swap the coins in positions 0 and 4:

that most of the planning and problem


solving that makes students successful
happens away from the computer.

Next, we swap the coins in positions 1 and 5:

HOW TO 6.1 Writing a Loop How To guides give step-by-step


This How To walks you through the process of implementing a guidance for common programming
loop statement. We will illustrate the steps with the following
example problem. tasks, emphasizing planning and
Problem Statement Read twelve temperature values (one for
each month) and display the number of the month with the high- testing. They answer the beginner’s
est temperature. For example, according to worldclimate.com, the
average maximum temperatures for Death Valley are (in order by question, “Now what do I do?” and
month, in degrees Celsius):
18.2 22.6 26.4 31.1 36.6 42.2 45.7 44.5 40.2 33.1 24.2 17.6
integrate key concepts into a
In this case, the month with the highest temperature (45.7 degrees problem-solving sequence.
Celsius) is July, and the program should display 7.

Step 1 Decide what work must be done inside the loop.

Every loop needs to do some kind of repetitive work, such as


• Reading another item.
• Updating a value (such as a bank balance or total).
• Incrementing a counter. Worked Examples apply
If you can’t figure out what needs to go inside the loop, start by writing down the steps that
the steps in the How To to a
WORKED EXAMPLE 6.1 Credit Card Processing different example, showing
Learn how to use a loop to remove spaces from a credit card
number. Go to wiley.com/go/javaexamples and download
how they can be used to
Worked Example 6.1.
plan, implement, and test
a solution to another
programming problem.
Table 1 Variable Declarations in Java
Variable Name Comment

int width = 20; Declares an integer variable and initializes it with 20.

int perimeter = 4 * width; The initial value need not be a fixed value. (Of course, width
must have been previously declared.)
String greeting = "Hi!"; This variable has the type String and is initialized with the
Example tables support beginners
string “Hi”. with multiple, concrete examples.
height = 30; Error: The type is missing. This statement is not a declaration
but an assignment of a new value to an existing variable—see These tables point out common
Section 2.2.5.
errors and present another quick
Error: You cannot initialize a number with the string “20”.
reference to the section’s topic.
int width = "20";
(Note the quotation marks.)
int width; Declares an integer variable without initializing it. This can be a
cause for errors—see Common Error 2.1 on page 42.
int width, height; Declares two integer variables in a single statement. In this
book, we will declare each variable in a separate statement.

bj5_fm_06.indd 9 10/24/12 6:28 PM


x Walkthrough

This means “compute the value of width + 10 1 and store that value in the variable
width 2 ” (see Figure 4).
Progressive figures trace code
In Java, it is not a problem that the variable width is used on both sides of the = sym-
bol. Of course, in mathematics, the equation width = width + 10 has no solution.
segments to help students visualize
the program flow. Color is used
1 Compute the value of the right-hand side consistently to make variables and
width = 30
other elements easily recognizable.
width + 10

40

2 Store the value in the variable Figure 3


1 Initialize counter
Execution of a for (int counter = 1; counter <= 10; counter++)
Figure 4 width = 40 for Loop {
Executing the Statement System.out.println(counter);
counter = 1 }
width = width + 10

2 Check condition
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }

3 Execute loop body


for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }

4 Update counter
for (int counter = 1; counter <= 10; counter++)
{

Students can view animations counter = 2 }


System.out.println(counter);

of key concepts on the Web.


A N I M AT I O N 5 Check condition again
for (int counter = 1; counter <= 10; counter++)
The for Loop {
System.out.println(counter);
counter = 2 }

The for loop neatly groups the initialization, condition, and update expressions
together. However, it is important to realize that these expressions are not executed
Self-check exercises at the together (see Figure 3).

end of each section are designed • The initialization is executed once, before the loop is entered. 1

to make students think through • The condition is checked before each iteration. 2 5
• The update is executed after each iteration. 4
the new material—and can
Write the for loop of the Investment class as a while loop.
spark discussion in lecture.
11.

SELF CHECK
12. How many numbers does this loop print?
for (int n = 10; n >= 0; n--)
{
System.out.println(n);
}

13. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
14. Write a for loop that computes the sum of the integers from 1 to n.

Practice It Now you can try these exercises at the end of the chapter: R6.4, R6.10, E6.8, E6.12.
Optional science and business
exercises engage students with •• Business E6.17 Currency conversion. Write a program

realistic applications of Java. that first asks the user to type today’s
price for one dollar in Japanese yen,
then reads U.S. dollar values and
converts each to yen. Use 0 as a sentinel.

• Science P6.15 Radioactive decay of radioactive materials can be


section_1/Investment.java modeled by the equation A = A0e-t (log 2/h), where A is
1 /** the amount of the material at time t, A0 is the amount
2 A class to monitor the growth of an investment that at time 0, and h is the half-life.
3 accumulates interest at a fixed annual rate.
4 */ Technetium-99 is a radioisotope that is used in imaging
5 public class Investment of the brain. It has a half-life of 6 hours. Your program
6 { should display the relative amount A / A0 in a patient
7 private double balance; body every hour for 24 hours after receiving a dose.
8 private double rate;
9 private int year;
10
11 /**
12 Constructs an Investment object from a starting balance and
13 interest rate.
14 @param aBalance the starting balance
15
16 */
@param aRate the interest rate in percent
Program listings are carefully
17 public Investment(double aBalance, double aRate)
18 { designed for easy reading,
19 balance = aBalance;
20
21
rate = aRate;
year = 0;
going well beyond simple
22
23
}
color coding. Methods are set
24
25
/**
Keeps accumulating interest until a target balance has off by a subtle outline.
26 been reached.
27 @param targetBalance the desired balance
28 */

bj5_fm_05.indd 10 10/18/12 3:25 PM


Walkthrough xi

Length and Size


Common Errors describe the kinds Common Error 7.4
Unfortunately, the Java syntax for Data Type Number of Elements
of errors that students often make, determining the number of elements
in an array, an array list, and a string Array a.length
with an explanation of why the errors is not at all consistent. It is a com-
mon error to confuse these. You just Array list a.size()

occur, and what to do about them. have to remember the correct syntax
for every data type. String a.length()

Programming Tip 5.5 Hand-Tracing


A very useful technique for understanding whether a pro-
gram 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. Hand-tracing helps you
For example, let’s trace the getTax method with the data understand whether a
Programming Tips explain from the program run above.
When the TaxReturn object is constructed, the income
program works correctly.

good programming practices, instance variable is set to 80,000 and status is set to MARRIED. Then the getTax method is called.
In lines 31 and 32 of TaxReturn.java, tax1 and tax2 are initialized to 0.
and encourage students to be 29 public double getTax()
30 {

more productive with tips and income status tax1 tax2


31 double tax1 = 0;
32 double tax2 = 0;
33 80000 MARRIED 0 0
techniques such as hand-tracing. Because status is not SINGLE, we move to the else
branch of the outer if statement (line 46).
34 if (status == SINGLE)
35 {
36 if (income <= RATE1_SINGLE_LIMIT)
37 {
38 tax1 = RATE1 * income;
39 }
40 else
41 {
42 tax1 = RATE1 * RATE1_SINGLE_LIMIT;
43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
44 }
45 }
46 else
47 {

Special Topic 11.2 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
Special Topics present optional 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 select-
topics and provide additional ing 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
explanation of others. New 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
features of Java 7 are also 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
covered in these notes. obtain a File object that describes the file. Here is a complete example:
FULL CODE EXAMPLE
JFileChooser chooser = new JFileChooser();
Go to wiley.com/go/ Scanner in = null;
javacode to download
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
a program that
{
demonstrates how to
use a file chooser. File selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
. . .
}

Call with
showOpenDialog
method

Computing & Society 1.1 Computers Are Everywhere


Button is “Save” when
When computers The advent of ubiqui-
showSaveDialog method
were first invented tous computing changed
is called
in the 1940s, a computer filled an many aspects of our
entire room. The photo below shows lives. Factories used
the ENIAC (electronic numerical inte- to employ people to
A JFileChooser Dialog Box
grator and computer), completed in do repetitive assembly
1946 at the University of Pennsylvania. tasks that are today car-
The ENIAC was used by the military ried out by computer-
Computing & Society presents social to compute the trajectories of projec- controlled robots, oper-
tiles. Nowadays, computing facilities ated by a few people
and historical topics on computing—for of search engines, Internet shops, and who know how to work
social networks fill huge buildings with those computers.
interest and to fulfill the “historical and called data centers. At the other end of Books, music, and mov-
the spectrum, computers are all around ies are nowadays often

social context” requirements of the us. Your cell phone has a computer consumed on com- This transit card contains a computer.
inside, as do many credit cards and fare puters, and comput-

ACM/IEEE curriculum guidelines.


cards for public transit. A modern car ers are almost always
has several computers––to control the involved in their production. The could not have been written without
engine, brakes, lights, and the radio. book that you are reading right now computers.

bj5_fm_05.indd 11 10/18/12 3:25 PM


xii Walkthrough

Web Resources

http://horstmann.com/codecheck/
CodeCheck “CodeCheck” is a new
online service currently in development
by Cay Horstmann that students can
use to check their homework and to
work on additional practice problems.
Visit http://horstmann.com/codecheck
to learn more and to try it out.

Test Bank Instructors can use quiz and


test questions designed to exercise
students’ code reading and writing skills.

10) What is displayed after executing the given code snippet?

int[] mymarks = new int[10];


int total = 0;
Scanner in = new Scanner(System.in);
for (int cnt = 1; cnt <= 10; cnt++)
{
System.out.print("Enter the marks: ");
mymarks[cnt] = in.nextInt();
total = total + mymarks[cnt];
}
System.out.println(total);

a) The code snippet displays the total marks of all ten subjects.
b) The for loop causes a run-time time error on the first iteration.
c) The code snippet causes a bounds error.
d) The code snippet displays zero.

Lab Exercises These multi-part


1.1) Consider the following Card class. exercises ask students to apply
public class Card
{
chapter concepts. They can serve
private String name; as “warm-ups” in the lab or to Animations Students can
public Card() provide additional practice. play and replay dynamic
{
name = ""; explanations of concepts
}
and program flow.
public Card(String n)
{
name = n;
}

public String getName()


{
return name;
}

public boolean isExpired()


{
return false;
}

public String format()


{
return "Card holder: " + name;
}
}

Use this class as a superclass to implement a hierarchy of related classes:

Class Data
IDCard ID number
CallingCard Card number, PIN
DriverLicense Expiration year

Write declarations for each of the subclasses. For each subclass, supply private instance variables. Leave the
bodies of the constructors and the format methods blank for now.

bj5_fm_06.indd 12 10/24/12 6:23 PM


Acknowledgments xiii

Acknowledgments
Many thanks to Beth Lang Golub, Don Fowley, Elizabeth Mills, Katherine Willis,
Jenny Welter, Wendy Ashenberg, Lisa Gee, Kevin Holm, and Tim Lindner at John
Wiley & Sons, and Vickie Piercey at Publishing Services for their help with this proj-
ect. 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 Suchindran Chatterjee, Arizona State University, Jose Cordova,
University of Louisiana, Udayan Das, DeVry University, James Johnson, Aaron
Keen, California Polytechnic State University San Luis Obispo, Norm Krumpe,
Miami University Ohio, Kathy Liszka, University of Akron, Kathleen O’Brien, San
Jose State University, Donald Smith, Columbia College, Mark Thomas, University of
Cincinnati, Laurie White, Mercer University, Brent Wilson, George Fox University,
and David Woolbright, Columbus State University, for their excellent contributions
to the supplementary materials.
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:

Eric Aaron, Wesleyan University Guy Helmer, Iowa State Bill Mongan, Drexel University
James Agnew, Anne Arundel University George Novacky, University
Community College Ed Holden, Rochester Institute of Pittsburgh
Greg Ballinger, Miami Dade of Technology Mimi Opkins, California State
College Steven Janke, Colorado College University Long Beach
Jon Beck, Truman State Mark Jones, Lock Haven Derek Pao, City University of
University University of Pennsylvania Hong Kong
Matt Boutell, Rose-Hulman Dr. Mustafa Kamal, University of Katherine Salch, Illinois Central
Institute of Technology Central Missouri College
John Bundy, DeVry University Gary J. Koehler, University of Javad Shakib, DeVry University
Chicago Florida Charlie Shu, Franklin University
Michael Carney, Finger Lakes Ronald Krawitz, DeVry Joslyn A. Smith, Florida
Community College University International University
Christopher Cassa, Norm Krumpe, Miami Robert Strader, Stephen F. Austin
Massachusetts Institute of University Ohio State University
Technology Jim Leone, Rochester Institute Jonathan S. Weissman, Finger
Dr. Suchindran S. Chatterjee, of Technology Lakes Community College
Arizona State University Kevin Lillis, St. Ambrose Katherine H. Winters, University
Tina Comston, Franklin University of Tennessee Chattanooga
University Darren Lim, Siena College Tom Wulf, University of
Lennie Cooper, Miami Dade Hong Lin, DeVry University Cincinnati
College Kuber Maharjan, Purdue Qi Yu, Rochester Institute of
Sherif Elfayoumy, University of University College of Technology
North Florida Technology at Columbus
Henry A Etlinger, Rochester Patricia McDermott-Wells,
Institute of Technology Florida International
University

bj5_fm_06.indd 13 11/9/12 11:56 AM


xiv Acknowledgments

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:

Tim Andersen, Boise State University Elliotte Harold Kai Qian, Southern Polytechnic
Ivan Bajic, San Diego State University Eileen Head, Binghamton University State University
Ted Bangay, Sheridan Institute Cecily Heiner, University of Utah Cyndi Rader, Colorado School
of Technology Brian Howard, Depauw University of Mines
Ian Barland, Radford University Lubomir Ivanov, Iona College Neil Rankin, Worcester Polytechnic
George Basham, Franklin University Norman Jacobson, University of Institute
Sambit Bhattacharya, Fayetteville California, Irvine Brad Rippe, Fullerton College
State University Curt Jones, Bloomsburg University Pedro I. Rivera Vega, University
Rick Birney, Arizona State University Aaron Keen, California Polytechnic of Puerto Rico, Mayaguez
Paul Bladek, Edmonds Community State University, San Luis Obispo Daniel Rogers, SUNY Brockport
College Mugdha Khaladkar, New Jersey Chaman Lal Sabharwal, Missouri
Joseph Bowbeer, Vizrea Corporation Institute of Technology University of Science and
Timothy A. Budd, Oregon State Elliot Koffman, Temple University Technology
University Kathy Liszka, University of Akron John Santore, Bridgewater State
Robert P. Burton, Brigham Young Hunter Lloyd, Montana State College
University University Carolyn Schauble, Colorado State
Frank Butt, IBM Youmin Lu, Bloomsburg University University
Jerry Cain, Stanford University John S. Mallozzi, Iona College Brent Seales, University of Kentucky
Adam Cannon, Columbia University John Martin, North Dakota State Christian Shin, SUNY Geneseo
Nancy Chase, Gonzaga University University Jeffrey Six, University of Delaware
Archana Chidanandan, Rose-Hulman Jeanna Matthews, Clarkson University Don Slater, Carnegie Mellon
Institute of Technology Scott McElfresh, Carnegie Mellon University
Vincent Cicirello, The Richard University Ken Slonneger, University of Iowa
Stockton College of New Jersey Joan McGrory, Christian Brothers Donald Smith, Columbia College
Teresa Cole, Boise State University University Stephanie Smullen, University of
Deborah Coleman, Rochester Institute Carolyn Miller, North Carolina Tennessee, Chattanooga
of Technology State University Monica Sweat, Georgia Institute
Jose Cordova, University of Louisiana, Sandeep R. Mitra, State University of Technology
Monroe of New York, Brockport Peter Stanchev, Kettering University
Valentino Crespi, California State Teng Moh, San Jose State University Shannon Tauro, University of
University, Los Angeles John Moore, The Citadel California, Irvine
Jim Cross, Auburn University Jose-Arturo Mora-Soto, Jesica Ron Taylor, Wright State University
Russell Deaton, University Rivero-Espinosa, and Julio-Angel Russell Tessier, University of
of Arkansas Cano-Romero, University Massachusetts, Amherst
Geoffrey Decker, Northern Illinois of Madrid Jonathan L. Tolstedt, North Dakota
University Faye Navabi, Arizona State University State University
H. E. Dunsmore, Purdue University Parviz Partow-Navid, California State David Vineyard, Kettering University
Robert Duvall, Duke University University, Los Angeles Joseph Vybihal, McGill University
Eman El-Sheikh, University of Kevin O’Gorman, California Xiaoming Wei, Iona College
West Florida Polytechnic State University, San Todd Whittaker, Franklin University
John Fendrich, Bradley University Luis Obispo Robert Willhoft, Roberts Wesleyan
David Freer, Miami Dade College Michael Olan, Richard Stockton College
John Fulton, Franklin University College Lea Wittie, Bucknell University
David Geary, Sabreware, Inc. Kevin Parker, Idaho State University David Womack, University of Texas
Margaret Geroch, Wheeling Jesuit Jim Perry, Ulster County Community at San Antonio
University College David Woolbright, Columbus State
Ahmad Ghafarian, North Georgia Cornel Pokorny, California University
College & State University Polytechnic State University, Catherine Wyman, DeVry University
Rick Giles, Acadia University San Luis Obispo Arthur Yanushka, Christian Brothers
Stacey Grasso, College of San Mateo Roger Priebe, University of Texas, University
Jianchao Han, California State Austin Salih Yurttas, Texas A&M University
University, Dominguez Hills C. Robert Putnam, California State
Lisa Hansen, Western New England University, Northridge
College

bj5_fm_06.indd 14 11/6/12 9:23 PM


Visit https://testbankfan.com
now to explore a rich
collection of testbank or
solution manual and enjoy
exciting offers!
CONTENTS

Preface iii
Special Features xxii

Chapter 1 Introduction 1
1.1 Computer Programs 2
1.2 The Anatomy of a Computer 3
1.3 The Java Programming Language 6
1.4 Becoming Familiar with Your Programming Environment 8
1.5 Analyzing Your First Program 12
1.6 Errors 15
1.7 Problem Solving: Algorithm Design 16

Chapter 2 Using Objects 33

2.1 Objects and Classes 34


2.2 Variables 36
2.3 Calling Methods 43
2.4 Constructing Objects 48
2.5 Accessor and Mutator Methods 50
2.6 The API Documentation 52
2.7 Implementing a Test Program   55
2.8 Object References   57
2.9 Graphical Applications   61
2.10 Ellipses, Lines, Text, and Color   66

Chapter 3 Implementing Classes 81

3.1 Instance Variables and Encapsulation 82


3.2 Specifying the Public Interface of a Class 86
3.3 Providing the Class Implementation 93
3.4 Unit Testing   102
3.5 Problem Solving: Tracing Objects 105
3.6 Local Variables 107
3.7 The this Reference 109
3.8 Shape Classes   112

xv

bj5_fm_05.indd 15 10/18/12 3:25 PM


xvi Contents

Chapter 4 Fundamental Data Types 131


4.1 Numbers 132
4.2 Arithmetic 139
4.3 Input and Output 147
4.4 Problem Solving: First Do it By Hand 154
4.5 Strings 156

Chapter 5 Decisions 179


5.1 The if Statement 180
5.2 Comparing Values 186
5.3 Multiple Alternatives 196
5.4 Nested Branches 200
5.5 Problem Solving: Flowcharts 207
5.6 Problem Solving: Selecting Test Cases   210
5.7 Boolean Variables and Operators 213
5.8 Application: Input Validation 218

Chapter 6 Loops 241


6.1 The while Loop 242
6.2 Problem Solving: Hand-Tracing 249
6.3 The for Loop 254
6.4 The do Loop 262
6.5 Application: Processing Sentinel Values 263
6.6 Problem Solving: Storyboards 269
6.7 Common Loop Algorithms 272
6.8 Nested Loops 279
6.9 Application: Random Numbers and Simulations 283
6.10 Using a Debugger   286

Chapter 7 Arrays and Array Lists 311

7.1 Arrays 312


7.2 The Enhanced for Loop 321
7.3 Common Array Algorithms 322
7.4 Problem Solving: Adapting Algorithms 331
7.5 Problem Solving: Discovering Algorithms by Manipulating
Physical Objects 336
7.6 Two-Dimensional Arrays 340

bj5_fm_05.indd 16 10/18/12 3:25 PM


Contents xvii

7.7 Array Lists 347


7.8 Regression Testing   356

Chapter 8 Designing Classes 379

8.1 Discovering Classes 380


8.2 Designing Good Methods 381
8.3 Problem Solving: Patterns for Object Data 390
8.4 Static Variables and Methods 395
8.5 Packages 400
8.6 Unit Test Frameworks 407

Chapter 9 Inheritance 421


9.1 Inheritance Hierarchies 422
9.2 Implementing Subclasses 426
9.3 Overriding Methods 431
9.4 Polymorphism 437
9.5 Object: The Cosmic Superclass 448

Chapter 10 Interfaces 463

10.1 Using Interfaces for Algorithm Reuse 464


10.2 Working with Interface Variables 471
10.3 The Comparable Interface 473
10.4 Using Interfaces for Callbacks 477
10.5 Inner Classes 481
10.6 Mock Objects 483
10.7 Event Handling 484
10.8 Building Applications with Buttons 490
10.9 Processing Timer Events 494
10.10 Mouse Events 497

Chapter 11 Input/Output and Exception Handling 513

11.1 Reading and Writing Text Files 514


11.2 Text Input and Output 519
11.3 Command Line Arguments 527
11.4 Exception Handling 534
11.5 Application: Handling Input Errors 545

bj5_fm_05.indd 17 10/18/12 3:25 PM


xviii Contents

Chapter 12 Object-Oriented Design 559

12.1 Classes and Their Responsibilities 560


12.2 Relationships Between Classes 563
12.3 Application: Printing an Invoice 569

Chapter 13 RECURSION 587

13.1 Triangle Numbers 588


13.2 Recursive Helper Methods 596
13.3 The Efficiency of Recursion 598
13.4 Permutations 603
13.5 Mutual Recursion 608
13.6 Backtracking 614

Chapter 14 Sorting and searching 629

14.1 Selection Sort 630


14.2 Profiling the Selection Sort Algorithm 633
14.3 Analyzing the Performance of the Selection Sort Algorithm 636
14.4 Merge Sort 641
14.5 Analyzing the Merge Sort Algorithm 644
14.6 Searching 648
14.7 Problem Solving: Estimating the Running Time of an Algorithm 653
14.8 Sorting and Searching in the Java Library 658

Chapter 15 The Java Collections Framework 671

15.1 An Overview of the Collections Framework 672


15.2 Linked Lists 675
15.3 Sets 681
15.4 Maps 686
15.5 Stacks, Queues, and Priority Queues 692
15.6 Stack and Queue Applications 695

Chapter 16 Basic Data Structures 715

16.1 Implementing Linked Lists 716


16.2 Implementing Array Lists 731
16.3 Implementing Stacks and Queues 735
16.4 Implementing a Hash Table 741

bj5_fm_05.indd 18 10/18/12 3:25 PM


Contents xix

Chapter 17 tree Structures 761

17.1 Basic Tree Concepts 762


17.2 Binary Trees 766
17.3 Binary Search Trees 771
17.4 Tree Traversal 780
17.5 Red-Black Trees 786
17.6 Heaps 793
17.7 The Heapsort Algorithm 804

Chapter 18 Generic classes 819

18.1 Generic Classes and Type Parameters 820


18.2 Implementing Generic Types 821
18.3 Generic Methods 825
18.4 Constraining Type Parameters 827
18.5 Type Erasure 831

Chapter 19 Graphical User Interfaces 841

19.1 Layout Management 842


19.2 Processing Text Input 846
19.3 Choices 852
19.4 Menus 863
19.5 Exploring the Swing Documentation 869

Chapter 20 Streams and Binary Input/Output 881

20.1 Readers, Writers, and Streams 882


20.2 Binary Input and Output 883
20.3 Random Access 887
20.4 Object Streams 893

Chapter 21 Multithreading (WEB ONLY)

21.1 Running Threads


21.2 Terminating Threads
21.3 Race Conditions
21.4 Synchronizing Object Access
21.5 Avoiding Deadlocks
21.6 Application: Algorithm Animation

bj5_fm_05.indd 19 10/18/12 3:25 PM


Exploring the Variety of Random
Documents with Different Content
nobleman was upon him, and, having issued several gruff orders to
his subordinates, he led the way along a beaten trail into the hills. As
they went, Prexaspes sought information.
“How long has the Prince been at his summer house?”
“Seven days only. He has just married a new wife, the daughter of
Nebuchadezer, Prince of Nineveh, and he has taken her there, as he
says, to be at peace, leaving his other wives at the palace.”
“Has he many people with him?”
“Oh, yes! Thirty notables of Nineveh came as an escort with the new
wife. Thirty Medean nobles are with them for company. Besides,
King Crœsus is there and also the son of Hillel of Damascus. There
be the Babylonian hostages and Gaumata, the chief Magian, and a
hundred others from far and near. A thousand cavalry guard the
camp. Great games have there been! The Prince has proven himself
to be a mighty archer and spear-thrower. He outshoots them all. Well
it is for them! For the liquor—you know?”
Merobates waved his hand suggestively towards his mouth as
though quaffing from a goblet. Prexaspes nodded assent.
“How is the Prince’s temper?” he asked.
“Excellent! Never better! His new wife pleases him and his servants
have learned how to avoid crossing him. But what is this news,
which you have galloped from afar to bring?”
“It is for the Prince’s ears first; but know, O Merobates, that great
fortune either of good or evil hangs over your head and mine to-day.
How does the Prince regard himself now?”
Merobates laughed.
“He has adopted the customs of the lowlander dogs who salaam to
the earth before royalty. Cambyses has forgotten that he is mortal
and swears that he will do even greater deeds than the Great King,
his father. If you would please him, prostrate yourself and bow very
low to the earth. Were he God himself, he could not be pleased more
with adulation and homage! Praise his deeds—he swells with pride.
Fail to praise—you may as well leap from the tower in the city
market! Please him—a gold chain and a chief place at feasts is your
reward! Displease him,—a bowstring at your throat, or hanging by
your heels to a beam, or some other evil! Me has he ever
commanded to treat him as ever I have,—with respect and
obedience, but not with lying adulation. I tell him his faults. He
laughs.”
“I remember, he used to say that Merobates was his conscience and
was the only man who dared to cross him or to speak plainly to him.”
“It has always been so. He is violent. He fears not to smite in wrath;
but he is subject to persuasion and art. He has no patience with
those whom he dislikes and he dislikes all who neglect to praise him.
Even the great Belteshazzer, appointed Governor of this province by
Cyrus, has not escaped his anger. The Prince has revoked his
authority.”
Presently they entered a canyon, in which a clear brook tumbled
over rocks. Following this they soon entered a small valley. Great
trees bordered the margin of the stream and were scattered over the
valley, forming a natural park. In the midst was the Prince’s palace, a
low structure built of hewn timbers. A score of lesser houses and
many tents stood at the sides of an open field several acres in
extent, which lay in front of the palace. On this field the sports and
contests of which Cambyses was fond were held.
Prexaspes now perceived a group of men gathered beneath the
spreading branches of a great live-oak near the palace. One, who
was seated on a thronelike chair higher than the others, was
engaged in conversation with another who stood uncovered before
him and whose dress indicated that he was a priest. Others standing
near appeared to be giving close attention. He who was seated was
a large, heavy-limbed man, well-padded with fat and short-necked
and gross. His big, round head was covered with a mass of curly
black hair and was encircled by a gem-studded coronet. His face
was dark, heavy, and flaccid, but his black eyes looked forth
shrewdly from beneath overhanging brows. Bushy eyebrows met
above his beaklike nose. A heavy black beard cut to a length of
about six inches covered the lower part of his face. He was a
powerful man physically and was said to be agile and quick in spite
of his fat.
Such was Cambyses, elder son of Cyrus. There were marks of
dissipation on his face. From early youth he had indulged his
passions, until now, at the age of thirty years, he was a slave to
them.
The sound of approaching hoofs called the Prince’s attention to
Prexaspes and his followers. He paused in his discourse and
exclaimed angrily: “Who comes? It must be very important service to
cause men to ride thus into my presence!”
Prexaspes halted at twenty paces’ distance, gave the reins of his
steed to Merobates, sprang to the earth and drew near, uncovering
his head as he advanced. Cambyses then recognized him and
uttered an exclamation of surprise and pleasure. Prexaspes,
throwing himself on his face at the Prince’s feet, cried: “All hail, King
of Kings! May the Great King of all the World live forever!”
For a moment, Cambyses was silent. He knew the meaning of those
words. His face paled and he sank back upon his seat. But
recovering he said, in a voice quivering with excitement: “Rise up,
Prexaspes! What mean you? Why are you here? What of my
father?”
“I will speak only if you bid me, mighty King!”
“Speak on!”
“King Cyrus, the Great King, the immortal hero, greater than
Jemshid, greater than Kaiomur, is no more alive! But there lives a
greater, even Cambyses, King of Kings, King of the Whole Earth;
and, to him bring I this message at the command of the noble
Hystaspis, King of Iran, thy subject. May I find forgiveness as a
bearer of this evil news of the death of thy father, and favor as a
bearer of the good news of thy accession to the throne!”
Cambyses was again silent, unable fully to realize his elevation to
supreme authority. His eyes turned upon his courtiers, who forthwith
fell on their faces before him, and cried out: “All hail, King of Kings!
Live forever!”
He drew a deep inspiration. Graciously extending his hand he
motioned to Prexaspes to rise and draw near; and, taking from his
own neck a heavy gold chain, he placed it around the messenger’s
neck, saying:
“I give you my favor, noble Prexaspes! A long and weary journey
have you come to bear me this news; and you shall be rewarded.
That has come to pass which had to come. Henceforth Cambyses,
the Achæmenian, son of Cyrus, heaven-born, reigns and shall reign!
I thank you, Prexaspes! You shall have room in my palace here and
shall feast this night. On the morrow we will return to our capital and
proclaim my accession to the throne. Sit down here on my right hand
and tell me of the death of my father. There shall be proclaimed
throughout the empire forty days of mourning for my father and, after
that, forty days of rejoicing for me.”
“I am indeed weary and travel-stained,” rejoined Prexaspes, looking
down upon his dusty clothes. “I have ridden day and night, that I
might hasten to you. I pray you command that I may retire and dress
as becomes one who stands in the presence of the King.”
“Mind not the clothes! It pleases me to note such eagerness in my
service. Ho, there, cup-bearer!” cried the King, turning to a youth
who stood waiting near the palace door. “Bring cups and wine!”
Instantly the cup-bearer clapped his hands. Two servants came
running from the palace, one bearing a jar of wine, the other a tray of
golden goblets. The goblets were quickly filled with ruby wine and
the cup-bearer presented them to the King, after duly tasting them.
Cambyses took one and handed it to Prexaspes.
“Drink!” he said. “You must be thirsty. But, perhaps, my father has
trained you to soberness?”
“While King Cyrus lived I obeyed him. Now that Cambyses is King of
Kings, I obey him,” answered Prexaspes, taking the cup.
“Well said!” exclaimed Cambyses, taking a huge goblet. “Come, let
us first pour a libation to the earth and its gods.”
He poured a little of the wine out upon the earth and drank the
remainder. Prexaspes followed suit. The King laughed as he looked
around upon his courtiers and saw that their countenances were
expressive of curiosity and mild astonishment. Pouring libations to
the gods of earth was sin with the orthodox Aryans and a new
practice to the majority of those present. But they expected that
Cambyses would disregard custom and law, even more now as King
than he did while only a prince.
“Now sit here by me and briefly tell how my father died and all that
happened thereafter,” said the King to Prexaspes. “Afterwards you
shall rest.”
Prexaspes sat down at the King’s right hand on a low bench. The
courtiers and attendants, obeying a motion of the King’s hand,
retired beyond hearing.
“I thank you, O King, for this favor!” answered Prexaspes. “My last
message was written just before your father encamped with his army
on the left bank of the Jaxartes and two days before the last great
battle. It had been in the King’s mind to cross the river and pursue
the enemy farther when he learned from his scouts and some
prisoners that the Touranians were gathering at a point ten
parasangs above us with the intention of giving battle. Then the King
set his army in battle-array, in a very strong position, with the left
wing resting on the river and the right far out in shifting sand-dunes.
In front was a deep, narrow water-course beyond which lay an open
plain over which the enemy must come. He commanded the Prince
of Iran to lead the Imperial Guard to a position behind the sand-
dunes, ready to come out upon the enemy’s flank and rear when the
battle should be joined.”
The King interrupted, exclaiming: “A young man is Prince Darius to
hold so important a command! By my beard! Infants shall not
command under me!”
“Your will is law, O King,” rejoined Prexaspes bowing. “But I must say
that Prince Darius is a most loyal subject of Cambyses and a very
brave and able general. King Cyrus took position at the left of our
army and the weight of the enemy’s charge fell upon that part. It was
a fearful struggle. My light-armed troopers went out to draw the
enemy to charge and, as commanded, fell back before the
thousands on thousands of shrieking, howling foemen. They
followed us into the great ditch in our front and pressed across. They
bore back the Persian and Medean heavy-armed infantry. They
broke through and would have ruined the army, had not King Cyrus
at the head of five thousand men of the Imperial Guard thrown
himself into the breach and held them back by most mighty
exertions! Then came the Prince of Iran and the remainder of the
Guard down from the right upon the rear of the enemy, crushing and
rolling them back into the Jaxartes. His charge saved the day. It was
magnificent. The light horses of the Touranians went down like
leaves before a gust of wind. But just as the victory declared for us,
the King received a poisoned dart in his throat and was borne from
the field by the noble Otanes. In spite of all that the surgeons could
do, he died that night.”
“What message did he leave?”
“King Hystaspis was in command of the army. He called a council of
officers and designated me as a messenger to bring to you the last
decree of the Great King. Here it is.”
Prexaspes drew a packet from a pouch at his belt and presented it to
the King. Cambyses eagerly unbound it and began to read. A dark
frown slowly gathered on his face. He suddenly cast the paper upon
the earth and set his foot upon it, while his gleaming eyes showed
bitter wrath.
“What!” he exclaimed. “Does he think to divide his empire and
confirm that hair-brained, beardless Bardya as ruler of Iran and
Persia? I say, it shall not be! I am King of Kings now, and I shall reign
alone! I will cut that young sprout off if he dare claim a shadow of
sovereignty! My father always hated me and loved Bardya. He
always did shield that boy from my wrath. Now he gives him the best
part of the kingdom! What if he does acknowledge me as overlord?
Is he not ambitious? He will ingratiate himself with the people and
then will attempt to overthrow me! King Hystaspis and his son,—they
doubtless will aid him!”
He rose and paced back and forth, swinging his arms and smiting his
hands together. Prexaspes also rose and, though standing in a
humble attitude, covertly watched the King.
“What say you?” demanded Cambyses, halting before Prexaspes.
Prexaspes, after some hesitation, answered: “Doubtless it was not
just in the Great King to make such provisions; but he was old and
very fond of Prince Bardya. Why allow the decree to be published?
There is no need until you are firmly established. Afterwards there
will be time to deal with the matter.”
The King silently stroked his whiskers a moment considering the
advice. It seemed shrewd and good. His wrath cooled somewhat. A
cunning look came upon his flushed countenance.
“That is good advice, Prexaspes!” he assented. “You shall be my
chief counselor. This decree shall be burned. None know its contents
but you and I. I count on your silence and will greatly reward you. If
you deceive me, no death shall be too severe for you!”
“Have no doubt of me, Great King! I am your servant and will do as
you bid. There is no decree. I have forgotten it. Let it not be seen of
men. But Bardya has a copy of it and the Persian nobles witnessed
it.”
He recovered the paper from the earth and restored it to Cambyses.
The latter laughed as he tore it in small pieces. Calling a servant to
bring a brazier of coals, he placed the fragments upon the embers
and watched them burn.
“Hark you, Prexaspes!” he then said. “This Bardya must not be
allowed to divide this kingdom. See to it! Great will be your reward.
The second place in the kingdom shall be yours. Do you
understand?”
Prexaspes considered a moment. He well understood the meaning
Cambyses sought to convey.
“I understand,” he then said. “Perhaps misfortune will overtake the
young man. Who knows?”
The King laughed harshly. “An accident perhaps! Rather than that
the empire be divided, one of us should die. The world is not large
enough to hold two kings when Cambyses is one of them! What do
you advise?”
Prexaspes thoughtfully contemplated the earth. The King impatiently
waited, glowering at him with the restless, cruel eyes of a tiger.
“Speak!” commanded the King at length. “Shall we send a force and
take him?”
“If it please you, O King, that I should offer advice, no. Bardya is
strong in the love of the Aryan race. He now dwells in the midst of
hosts of stout men who are his friends and who would overthrow
your throne if they could for his sake. Persian and Medean soldiers
cannot be compelled to make war upon Bactrians when led by a son
of Cyrus. Babylon, Assyria, Damascus, Sardis, and the Ionian cities
will not uphold your hands; they but wait for an opportunity to rebel.
You must court the favor of the Aryan race. Above all I advise that
you show favor to the King of Iran and to his able son. They are the
idols of the veteran army of Cyrus.”
“But Darius is Bardya’s friend!”
“True, but he is also your loyal supporter.”
“How know you? Is it not said openly among the nobles of Persia
that Hystaspis by right of birth should have ruled instead of Cyrus?
Darius is ambitious. I know that youth! I have hated him since my
father showed more favor to him and to Bardya than to me! He
knows this. How then say you he will be my supporter?”
“Do you not remember his love of truth and his hatred of lies and
deception from his boyhood up?”
“I remember! No doubt it was a disease in him!”
“Just so! Nevertheless it is said throughout Persia and Iran and by
every man of the great army, that, when once the word of the Prince
of Iran is given, it will stand forever. No one ever requires of him a
witness or a written tablet. Now at the request of Cyrus and with
consent of his father, he placed his hands in those of the Great King
and swore to support you and Bardya on the throne of this empire.
Therefore you need not fear him; but, rather, you may depend upon
him for aid if you need it.”
The cloud on the King’s face lifted somewhat. He had watched with
jealous eye the growing power of the young Hystaspis and had
feared him even more than Bardya.
“Nevertheless, wait till his ambition meets opportunity,” he
suggested.
“No, it is as I say. I have proof. On the march to Bactra, the Prince
with the Imperial Guard was in charge of the transport of the King’s
body. The Guard, on the morning of the second day’s march, saluted
Darius as King of Kings; and all had taken oath to support him if he
would consent. But he rebuked them, told them of his oath to support
you, and then and there made them also swear with uplifted hands
to support you. I myself witnessed it.”
“Is it so? Treason must be flourishing indeed!” exclaimed Cambyses,
bitterly. “This Guard shall no longer be the Imperial Guard! It shall be
decimated!”
Rage again possessed the King’s soul. He knew himself to be
unpopular save with a few boon companions. His jealous heart was
filled with hatred towards the popular Prince. Prexaspes ventured to
remonstrate.
“Let not the Great King be offended with his servant! I am acquainted
with the army and all its soldiers. The Aryans are a proud race and
the nobles will not bow the knee even to their kings, as you know. Do
not anger them. Without them your subject nations will revolt and
you will have no one to support your empire. Rather, dissemble your
feelings. You are very wise, O King, if you but stop to think. First, be
well established on your throne. After the body of your heroic father
shall have been placed in its tomb, send the Prince and his Guard to
conquer new provinces. Be advised by me in this. Should evil befall
his son, old Hystaspis would lead the veterans of Cyrus five hundred
thousand strong against you. Who could stand before them?”
Cambyses ceased pacing back and forth and sat down, saying:
“Your words are wise, Prexaspes. I will be advised. Proceed!”
Prexaspes smiled slightly behind his hand. He had properly gauged
the King’s impulses. He continued: “I advise that you issue your
formal decree as King of Kings to-morrow and send copies thereof to
be proclaimed in every province of the empire; that you issue a
decree confirming the Prince of Iran in command of the Guard and in
his mission to transport the body of the Great King to Pasargadæ;
that you send a messenger to Bardya and to your sisters greeting
them kindly; that you, also, as soon as they shall have arrived at
Hamadan, show them all honor, go with them to do honor to Cyrus at
Pasargadæ, and dissemble your real feelings. Thus will you begin
wisely and thus will you please the Aryan people. Afterwards we may
take counsel; and, should Bardya meet with an accident or
disappear, who can blame the Great King? Be assured, O King, that
I advise well! I know that upon you only may I depend for
advancement and power. Bardya does not, nor do any of the great
Persian nobles, love Prexaspes. Their semi-barbaric manners suited
not my taste, and my refined manners were not approved by them!”
“I will heed your advice,” said the King. “My favor shall be with you.
First, I will make you Satrap of Medea. I will let that old Hebrew,
Belteshazzer, rest from his labors in his tower. Afterwards, if you
serve me well, I shall increase your power. See to it, Prexaspes, that
my will be not thwarted! There shall be one King, who shall be King
of Kings, and he must be Cambyses!”
“It shall be as you wish. But let us proceed with all care.” Thus
Prexaspes entered upon a road to great gain in wealth and power,
but also to ultimate woe.
The King presently dismissed Prexaspes, and the latter was
conducted to pleasant rooms in the palace, where he refreshed
himself with a bath, arrayed himself in clean linen and rich garments
and had himself barbered and perfumed by the King’s own barbers.
Cambyses was lavish with his favorites, and just now Prexaspes was
chief of them. The latter sat at the King’s right hand at dinner that
evening. All festivities were abandoned in honor of the dead King,
but the many courtiers who ate at his tables found opportunity to
assure the new King of their joy over his accession to the throne. He
drank deeply both of adulation and wine until he became half-drunk
and maudlin, whereupon Merobates took him almost forcibly to his
bedchamber.
Next day, the King and all his retinue returned to Hamadan. A royal
decree was immediately issued, reciting the death of the Great
Cyrus and the accession of Cambyses to the throne of the world,
and commanding all officers, soldiers, and peoples to acknowledge
him King of Kings. The royal treasury was opened. From it the
golden crown studded with precious gems, which Cyrus had worn on
state occasions, and the royal scepter were brought forth. Clad in
purple, and having the high, pointed crown on his head, his royal feet
encased in yellow shoes, and his hair and whiskers curled,
powdered, and perfumed, Cambyses held his first court in the great
audience room of the palace. He sat on a golden throne placed high
up on a dais, with fan-bearers waving ostrich plumes over him, with
Prexaspes standing at his right hand and Merobates at his left,
bearing the King’s sword and shield. He placed the crown on his
head with his own hands, while a loud-voiced herald recited his titles.
Then the thousand nobles and officers who were in attendance fell
on their faces to the floor before him and hailed him King of Kings,
the Great King! Cambyses, swelling with pride, deemed himself
divine, and as a god he looked down upon his subjects with haughty
demeanor.
The world thus acquired a new ruler.
CHAPTER VI
PERSEPOLIS

THE modern world knows little of the beauty and grandeur of ancient
Anshan, the home of Cyrus, or of the province of Fars and its cities.
Mountains shut off from them the hot winds of the Persian Gulf and
of the northern deserts. The high valleys lying between the mountain
ranges that extend across it like huge dikes are of surpassing
loveliness. Romantic woodlands, dells, lakes, canyons, murmuring
brooks, rushing rivers, far vistas, plains, mountains, and hills delight
the soul. In the valleys, flowers perfume the air all the year, and
vegetation, where irrigation is practiced, is luxuriant. On the high hills
and mountain tops winter holds sway during three or more months
and the seasons are well-marked as in the temperate zones. It is the
land of Omar, of Firdusi, and of many lesser poets; the land of an
ancient white race, whose rugged virtues made them lords of much
of the earth, but whose descendants have degenerated by admixture
with lower grades of humanity and have suffered much to maintain
even their own independence.
The celebrated plain of Mervdasht is between two parallel ranges of
mountains, one of which lies to the west between it and the low hot
lands of the gulf-coast and the other to the east between it and the
vale of Murghab, or ancient Anshan. A river comes down from the
northern mountains through the midst of this plain and empties into a
lake. It is a perennial stream, but fordable save in the winter when
the rains fall. It has been variously named, anciently the Araxes, later
the Kur or river of Cyrus, and again the Bendamir. Another river of
less volume but more celebrated, the Pulwar, comes down to join it
through the mountains from northeast table-lands. This passes by
the vale of Murghab, where a little stream of that name, coming from
the east, flows into it. In this vale was ancient Anshan, the capital of
the Achæmenian line of kings, a city also known as Pasargadæ. The
tortuous bed of the Pulwar connects the vale of Murghab with the
valley of Mervdasht, having cut for itself a deep gorge through the
mountains. A royal road, passing through this gorge or canyon,
connected the ancient capital with a more modern city, Persepolis.
Persepolis, or the city of the Persians, ancient Parsa, lay close to the
mouth of the mighty canyon of the Pulwar, where it opened into the
vale of Mervdasht. The city lay principally on the northern banks of
the river. On the southern bank was a great park; and in this on a
plateau extending from the base of low mountains that border the
eastern side of the plain, were the palaces of the Kings of Iran. King
Hystaspis and his great son, Darius, and his grandson, Xerxes, each
erected magnificent palaces of dark-gray marble on this natural
platform. The great size and magnificent architecture of these
buildings were among the wonders of the ancient world. Their
majestic ruins yet testify to the power, the love of art, and the
learning of those masters of men.
King Hystaspis, content to rule Iran as a nominal vassal of Cyrus and
under the shadow of his mighty arm, laid out for himself in the valley
of Merv a new city and there placed his loved friends and retainers.
He brought artisans from Egypt, Canaan, Syria, Phœnicia, and
distant Greece, and built for himself a great palace. It is said that he
or his son formulated a new alphabet for his language and caused
the books of Zoroaster to be translated therein.
Orchards of apple, peach, and apricot, vineyards where grape and
berry grew, fields of vegetables and grain, covered the fertile valley
and its surrounding hills. On the day when the Imperial Guard,
escorting the body of the Great Cyrus, halted on the summit of the
western ridge bounding the valley and looked down upon the
peaceful scene, autumn was touching all with the signs of harvest
and the coming winter-rest. On that day, while the funeral car halted,
Prince Bardya, his sisters, and the Prince of Iran rode forward to a
bluff jutting out from the ridge; and from this position they looked
down into a paradise,—so it seemed to them, weary with dusty roads
and desert lands. There, where the Pulwar entered the plain from the
narrow gorge in the western mountains, Cyrus had drawn up his
Persian patriots to fight a last battle for liberty from the Medean yoke,
having been driven to bay by the vast army of stern old Astyages, his
grandfather. That decisive battle not only gave liberty to his own
province but gave Astyages to him as a prisoner and the crown of
Medea for his own head. From that victory Cyrus had gone forth to
conquer the world. But now, conquered by the last enemy, Death, he
was returning there to his final rest. The heart of the Prince of Iran
was stirred by strong emotions, as he looked across the beautiful
vale. He could see afar the great portico of his father’s palace where,
he knew, his mother stood watching for the coming of her son.
Uncovering his head, he extended his hands towards heaven,
saying:
“To thee, O Ahura-Mazda, Ruler of Heaven, Giver of Life, Lover of
Truth, and Protector, we give thanks! For thou hast brought us
home!”
“Amen and amen!” exclaimed Bardya, uncovering his head.
The Prince of Iran then addressed his companions: “I welcome you
to the home of King Hystaspis. This valley and yonder city are his
property, ceded to him as a home for the Achæmenian family, when
he consented to remove hither from Bactra. I bid you rest at our
palace yonder this night. The road from Parsa to Anshan is rough
and ought to be traveled only by day. My mother is at the door to
welcome you.”
“We gladly accept!” assented Bardya, heartily. “Do I not love that
mother almost as much as you? Do you remember the happy days
when we hunted on yonder hills and swam in the Pulwar and the
Araxes? Do you remember the day we were almost drowned? We
will go to that deep water-hole again to-morrow and swim there as
boys again. Our troopers should rest a day while we send a
message to Cambyses at Anshan to inform him of our coming.”
Athura added: “It will be delightful to accept the hospitality of your
mother. I shall return after going to Anshan and shall stay long with
her and rest. My sister is much in need of rest. The long journey has
made her ill.”
“After we shall have accomplished our mission,” said the Prince of
Iran, “we shall enjoy many pleasant days there. The hunting is good.
We shall enjoy the royal sport!”
“Unless Ahriman interfere!” added Bardya, waving his hand towards
Anshan, where his brother now awaited their coming. “I propose to
stay a month at least. I suppose he awaits us impatiently at Anshan.”
Athura said reprovingly to her brother: “Speak not of the King of
Kings thus! He has sent us courteous messages, even if he would
not await us at Hamadan or march with us here. Perhaps it was best
that he should go on ahead to prepare the tomb and to arrange for
the ceremonies. Be advised, brother! Remember to show him the
deference due to his station. His anger was ever terrible! Now he
has no one to restrain him.”
Bardya laughed and tossed his head, as he answered: “Fear not for
me! I shall treat him with all due respect. Am I not on the ground my
father gave me in his will? The Persian lords will not permit him to
oppress us. When I see that King of Kings, I will demand of him that
he publish the full terms of my father’s will. If he refuse to observe
that—Well, it may be that he will cease to reign!”
The Prince of Iran said nothing, but his countenance was somber.
He feared that the impetuous Bardya would precipitate trouble. He
foresaw civil war.
Descending into the valley, they approached Persepolis. A vast
throng of people came out to meet them and stood on either side of
the road weeping and wailing aloud as the funeral car passed. A
company of guards led by an aged veteran met them at the entrance
of the city.
Prince Darius greeted the leader warmly: “Ho, Orobates, our beloved
High Chamberlain! How fares my royal mother?”
“All hail, Prince of Iran!” cried the stately old man, kissing the
Prince’s cheeks as the latter bent down to greet him. “God’s blessing
of long life and happiness be upon you! How good it is to behold you
once more! Your mother, our most gracious Queen, is well and
awaits you at the palace. She begs that you will prevail upon the
royal Bardya and his sisters to honor her house with their presence.
All things are prepared. The best of the herds, the finest game from
the mountains, the daintiest fruits and flowers,—all are ready!”
“They have consented to honor us, Orobates. Has my mother good
health and is she happy?”
“Excellent health, gracious Prince; but she sighs much for you and
the King.”
“Did Cambyses, the Great King, honor our house with his
presence?”
“He refused our bidding on the plea that he was in haste to reach
Anshan on state business. But he sent a gracious greeting to your
mother.”
The Prince led the caravan into the city, nodding and waving
greeting to many whom he had known when a child. Crossing the
Araxes over a magnificent stone bridge, the cortège marched into
Persepolis and encamped in a great open field on the shore of the
Pulwar. The funeral car was driven into the sacred enclosing wall of
a temple and there rested till a messenger went to Cambyses and
returned.
Leaving the cares of the encampment to subordinates, the Prince of
Iran, accompanied by Gobryas and some of his chief officers,
conducted Bardya and his sisters across the Pulwar over a beautiful
stone bridge of one great arch and through the park to his father’s
palace. The limpid stream, the great oaks, elms, walnuts, and plane
trees, whose foliage was tinged with gold and red, the flowering
shrubs, the fountains, and the greensward, smiled a joyful welcome
to the weary travelers. Broad steps, leading up to the great plateau
or bench on which the palace stood, gleamed white through the tree-
limbs. Slender gray columns adorned the portico. On the stairs stood
a group of women, and among them a stately dame, who waved her
hand in welcome. Prince Darius galloped on ahead to the foot of the
steps and, leaving his horse in charge of an attendant, ran up into
the embrace of his mother.
Age had not greatly affected the beauty of the Queen of Iran nor
dimmed her blue eyes. Her gray hair was gathered in a net at the
back of her head and was encircled by a golden band set with
sparkling gems. Her dress was an ample purple robe reaching to her
feet and encircled at the waist with a silken sash. Its loose sleeves
revealed arms still shapely and adorned with bracelets of gold. The
gracious majesty of her countenance, the sweetness of her smile,
and the soft accents of her voice were celebrated in Iran.
That was an age when wife and mother were not slaves or prisoners.
Recognized as the equal of men, their virtues and loveliness made
homes where men were grown. Not yet had Cambyses, aping the
manners and customs of the dwellers in Mesopotamia, Syria, and
Arabia, degraded women to the seclusion of harems; nor had
custom forbidden women to appear before friends unveiled, though
veils were commonly worn in public places. Polygamy was almost
unknown in Iran, though its practice had crept into Medea. The wife
was queen of the home and ruled in the heart of her husband.
The Prince knelt at his mother’s feet, and her arms encircled his
neck while her lips kissed his brow. “Welcome home, beloved son!”
she exclaimed. “Long days have intervened since you waved
farewell to me from yonder bridge; but no day has passed that I did
not think of you!”
She raised him up and stood proudly at his side, leaning on his arm,
while she welcomed Prince Bardya and his sisters. To Bardya she
said as he bent his knee before her: “The blessing of Ahura-Mazda
be upon you, O Prince of the World! Arise! It is not meet that you
kneel to me! Welcome to the palace of my lord, the King of Iran!”
“Gracious Queen,” replied Bardya as he arose, “I kneel to you as to
my mother! Next to her, who lives only in my memory, do I love and
reverence the mother of my friend, the Prince of Iran. Have we not,
in years past, stood together at your knee and received your
instruction? Now that we are indeed orphans we come to you for
consolation.”
Tears filled the great lady’s eyes. She embraced Athura and
Artistone tenderly; and, leaving the men to the care of her son, she
took the girls with her to her own apartments and personally saw that
they were made comfortable. While they are removing the dust of
the road and enrobing themselves for dinner, we may wander in
spirit through this typical palace of the Achæmenian kings and
observe its grandeur.
From the portico which extended the full breadth of the palace front,
an entrancing view of valley and mountain, of river and park, could
be had. Sixteen slender, fluted, marble pillars supported the massive
wooden roof of the portico. Their capitals were winged bulls; their
bases were bell-shaped and carved to imitate lotus buds. A high,
narrow door gave entrance from the front through the thick stone
walls into a hall, on either side of which were rooms where the
palace-guards had their abode. The hall led into a reception room
fully fifty feet square, whose walls were pierced by a dozen narrow
windows and whose ceiling of heavy carved timbers was upheld by
slender wooden pillars covered with silver plates. The stone walls
were hidden by beaten silver plates and the windows and doors
were hung with tapestries of fine crimson and purple fabrics.
Wooden shutters were fitted to the windows, but were now open to
admit air and light. Later, when winter should come with its rains and
frost, the windows would be closed by semi-transparent oiled silk.
Red and purple rugs lay on the tiled floor, partially covering the
various patterns worked out in colored tiles. A throne, shining with
gold plate, occupied a raised platform at the end of the room
opposite the entrance. Cushioned chairs, divans, and couches,
tables of polished wood, mirrors of polished silver and bronze, lamps
of many patterns fastened to the pillars and walls, and a cabinet of
dark inlaid wood comprised the furniture. The cabinet held a
collection of books, rolls, and tablets, the library and the special
treasure of the King of Iran.
Doors at the right of the throne led into the apartments of the men; at
the left, into the apartments of the women; and, immediately at the
rear, into a small open court, beyond which were the servants’
quarters. Banquets of state were held in the throne room, but
ordinarily the tables were laid in the small open court. The various
apartments were furnished with couches, and with blankets and rugs
of skillful weaving and of that fineness and texture for which the
woven products of Iran have ever been famous. All the
conveniences of an advanced civilization, which power and wealth
could provide or gather from the many nations over which the
Persians held sway, were here. Baths and toilets fed by water piped
from the hills, and drained into the Pulwar below, ornamental
cabinets, containing scents and cosmetics for adorning the person,
wardrobes full of costly dresses made of silk and fine linen, mirrors,
combs, and brushes—even the modern homes of many so-called
civilized people could boast no better.
A narrow stair led up from the inner court to the flat roof, where the
occupants of the palace, reclining on soft divans, under canopies or
sunshades, could pass the warmer hours of the day, breathe the
cool mountain air, and enjoy the lovely scenes. Looking down from it,
one could see the royal stables five hundred paces to the south in
the park, where scores of graceful horses were kept; and farther on
was the inclosure where cattle and sheep, driven in from the
mountain pastures, were ready to furnish the royal table with meat or
milk. A canal led from the Pulwar above the palace through the park
to the stables below and thence into luxuriant gardens where
servants toiled to supply their master’s table with vegetables. Fowls,
dogs, horses, and cattle enlivened the barnyard scene. Servants in
gay tunics, loose, fringed trousers, and with sandaled feet went
hither and thither on their duties. Guards in shining armor walked
their beats through the park or lazily stood leaning on their spears at
the palace steps.
While the guests were removing the dust and stains of travel,
servants busily prepared the banquet. Tables of walnut, plated with
silver and bound together by golden bands fastened with copper
nails, were set in the great audience hall. Platters of beautiful
porcelain or of beaten silver, piled high with fruits and bread, were
placed on them, and plates of silver and cups of gold were also
brought forth. Low seats whereon the guests could either sit or
recline were set in order. A major-domo in gorgeous livery saw that
all things were made ready. Then the guests were called. The men
were seated at one table; the women, at another. Prince Darius sat
at the head of the former; his mother at the head of the latter.
Servants brought on, in regular courses, fish, steaming loads of
venison and fowl, and bountiful supplies of vegetables and pastry.
Water, milk, and wine of Helbon were the drinks, the latter being
used sparingly. With appetites sharpened by a long day’s journey in
the bracing air of the mountains, the guests did full justice to the
viands. While they ate, the soft music of harps, played with
considerable skill by musicians in the court, floated in through the
open doors.
The banquet hour having passed, the officers and nobles returned to
the camp, while Prince Bardya and his sisters accompanied Prince
Darius and his mother to a room adjacent to the dining-hall, used by
the King of Iran when at home as an office. A large fireplace in one
corner of the room was filled with a cheerful blaze. Gathered about
the fire, guests and hosts felt much at home and spent a pleasant
hour in conversation.
“Now that Cambyses passed through your city with scant courtesy,”
Bardya said, somewhat warmed by the wine he had imbibed and by
his genial surroundings, so that he felt called upon to express his
indignation towards his brother, “what think you of such a king?” He
addressed Queen Hystaspis.
“I marvel not at his action,” she replied quietly. “He was never kindly
disposed towards us. But it is not for us to find fault. I should have
met him in person and given the invitation to stop with us. I would
have so done, had I not heard that he believes, with the Medes, that
women have no place in the affairs of men. He passed through our
city in a closed litter, not even deigning to see our messengers. He
made reply through his chamberlain that the King of Kings was
indisposed and pressed for time and would not rest till he should
arrive at his palace in Anshan.”
“He has ever been ill-natured!” continued Bardya, bitterly. “He
believes himself heaven-born! He will end by declaring himself a god
and appointing set times to worship him! What think you the nobles
of Persia will say of his manners? It is said he has determined to
decree a law of polygamy, and, like the Arabs, fill a harem with many

You might also like