Data Abstraction Problem Solving With Java Walls and Mirrors 3rd Ed Prichard PDF Download
Data Abstraction Problem Solving With Java Walls and Mirrors 3rd Ed Prichard PDF Download
https://ebookbell.com/product/data-abstraction-problem-solving-
with-java-walls-and-mirrors-3rd-ed-prichard-21347466
Data Abstraction And Problem Solving With Java Walls And Mirrors Us Ed
Frank M Carrano
https://ebookbell.com/product/data-abstraction-and-problem-solving-
with-java-walls-and-mirrors-us-ed-frank-m-carrano-6853392
https://ebookbell.com/product/instructors-manual-data-abstraction-and-
problem-solving-with-java-walls-and-mirrors-3rd-edition-janet-
prichard-12031300
Data Abstraction Problem Solving With C Walls And Mirrors 7th Edition
Frank M Carrano
https://ebookbell.com/product/data-abstraction-problem-solving-with-c-
walls-and-mirrors-7th-edition-frank-m-carrano-48690752
https://ebookbell.com/product/data-abstraction-problem-solving-with-c-
walls-mirrors-5th-edition-frank-m-carrano-33556412
Data Abstraction Problem Solving With C Walls And Mirrors 6th Edition
Frank M Carrano Timothy Henry
https://ebookbell.com/product/data-abstraction-problem-solving-with-c-
walls-and-mirrors-6th-edition-frank-m-carrano-timothy-henry-43272352
https://ebookbell.com/product/data-abstraction-problem-solving-with-c-
international-edition-6th-edition-frank-m-carrano-10881198
Data Abstraction And Problem Solving With C Walls And Mirrors 3rd
Edition Frank M Carrano
https://ebookbell.com/product/data-abstraction-and-problem-solving-
with-c-walls-and-mirrors-3rd-edition-frank-m-carrano-2526458
Data Structures Abstraction And Design Using Java 6th Edition Elliot B
Koffman
https://ebookbell.com/product/data-structures-abstraction-and-design-
using-java-6th-edition-elliot-b-koffman-4986366
Data Structures Abstraction And Design Using Java 3rd Elliot Koffman
https://ebookbell.com/product/data-structures-abstraction-and-design-
using-java-3rd-elliot-koffman-5529920
Data Abstraction
& Problem Solving
with JAVA™
WA L L S
AND
MIR R OR S
This page intentionally left blank
Data Abstraction
& Problem Solving
with JAVA™
WA L L S
AND
MIR R OR S
3rd Edition
Janet J. Prichard
Bryant University
Frank Carrano
University of Rhode Island
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this text-
book appear on appropriate page within text.
Authorized adaptation from the United States edition, entitled Data Abstraction and Problem Solving with
Java: Walls and Mirrors, 3rd edition, ISBN 978-0-13-212230-6 by Frank M. Carrano and Janet J. Prichard
published by Pearson Education © 2011.
If you purchased this book within the United States or Canada you should be aware that it has been imported
without the approval of the Publisher or the Author.
All rights reserved. Manufactured in the United States of America. This publication is protected by
Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction,
storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopy-
ing, recording, or likewise.
Many of the designations by manufacturers and seller to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the publisher was aware of a trademark claim, the designa-
tions have been printed in initial caps or all caps.
10 9 8 7 6 5 4 3 2 1—CRS—14 13 12 11 10
PART ONE
Problem-Solving Techniques 25
1 Review of Java Fundamentals 27
2 Principles of Programming and Software Engineering 105
3 Recursion: The Mirrors 161
4 Data Abstraction: The Walls 221
5 Linked Lists 265
PART TWO
Problem Solving with Abstract
Data Types 337
6 Recursion as a Problem-Solving Technique 339
7 Stacks 375
8 Queues 433
9 Advanced Java Topics 479
10 Algorithm Efficiency and Sorting 529
11 Trees 585
12 Tables and Priority Queues 667
13 Advanced Implementations of Tables 723
14 Graphs 801
15 External Methods 847
APPENDICES
A A Comparison of Java to C++ 887
B Unicode Character Codes (ASCII Subset) 891
C Java Resources 892
D Mathematical Induction 894
Glossary 901
Self-Test Answers 921
Index 945 5
This page intentionally left blank
Contents
Preface 15
Chapter Dependency Chart 18
PART ONE
Problem-Solving Techniques 25
1 Review of Java Fundamentals 27
1.1 Language Basics 28
Comments 28
Identifiers and Keywords 28
Variables 28
Primitive Data Types 29
References 30
Literal Constants 30
Named Constants 31
Assignments and Expressions 32
Arrays 35
1.2 Selection Statements 38
The if Statement 39
The switch Statement 40
1.3 Iteration Statements 41
The while Statement 41
The for Statement 42
The do Statement 45
1.4 Program Structure 45
Packages 46
Classes 47
Data Fields 48
Methods 50
How to Access Members of an Object 54
Class Inheritance 54
7
8 Contents
PART TWO
Problem Solving with Abstract
Data Types 337
6 Recursion as a Problem-Solving Technique 339
6.1 Backtracking 340
The Eight Queens Problem 340
6.2 Defining Languages 345
The Basics of Grammars 346
Two Simple Languages 347
Algebraic Expressions 350
6.3 The Relationship Between Recursion and Mathematical Induction 360
The Correctness of the Recursive Factorial Method 360
The Cost of Towers of Hanoi 361
Summary 363 Cautions 363 Self-Test Exercises 364
Exercises 364 Programming Problems 368
7 Stacks 375
7.1 The Abstract Data Type Stack 376
Developing an ADT During the Design of a Solution 376
7.2 Simple Applications of the ADT Stack 382
Checking for Balanced Braces 382
Recognizing Strings in a Language 386
7.3 Implementations of the ADT Stack 387
An Array-Based Implementation of the ADT Stack 389
A Reference-Based Implementation of the ADT Stack 391
An Implementation That Uses the ADT List 393
Comparing Implementations 395
The Java Collections Framework Class Stack 395
7.4 Application: Algebraic Expressions 397
Evaluating Postfix Expressions 397
Converting Infix Expressions to Equivalent Postfix Expressions 399
Contents 11
12.2 The ADT Priority Queue: A Variation of the ADT Table 687
Heaps 691
A Heap Implementation of the ADT Priority Queue 700
Heapsort 702
12.3 Tables and Priority Queues in the JCF 705
The JCF Map Interface 705
The JCF Set Interface 709
The JCF PriorityQueue Class 713
Summary 715 Cautions 716 Self-Test Exercises 716
Exercises 717 Programming Problems 720
13 Advanced Implementations of Tables 723
13.1 Balanced Search Trees 724
2-3 Trees 725
2-3-4 Trees 745
Red-Black Trees 752
AVL Trees 755
13.2 Hashing 761
Hash Functions 765
Resolving Collisions 767
The Efficiency of Hashing 776
What Constitutes a Good Hash Function? 779
Table Traversal: An Inefficient Operation under Hashing 781
The JCF Hashtable and TreeMap Classes 782
The Hashtable Class 782
The TreeMap Class 785
13.3 Data with Multiple Organizations 788
Summary 793 Cautions 794 Self-Test Exercises 795
Exercises 795 Programming Problems 798
14 Graphs 801
14.1 Terminology 802
14.2 Graphs as ADTs 805
Implementing Graphs 806
Implementing a Graph Class Using the JCF 809
14.3 Graph Traversals 812
Depth-First Search 814
Breadth-First Search 815
Implementing a BFS Iterator Class Using the JCF 817
14.4 Applications of Graphs 820
Topological Sorting 820
Spanning Trees 823
Minimum Spanning Trees 828
14 Contents
Welcome to the third edition of Data Abstraction and Problem Solving with
Java: Walls and Mirrors. Java is a popular language for beginning computer
science courses. It is particularly suitable to teaching data abstraction in an
object-oriented way.
This book is based on the original Intermediate Problem Solving and Data
Structures: Walls and Mirrors by Paul Helman and Robert Veroff (© 1986 by
Benjamin Cummings Publishing Company, Inc.). This work builds on their
organizational framework and overall perspective and includes technical and
textual content, examples, figures, and exercises derived from the original
work. Professors Helman and Veroff introduced two powerful analogies, walls
and mirrors, that have made it easier for us to teach—and to learn—computer
science.
With its focus on data abstraction and other problem-solving tools, this
book is designed for a second course in computer science. In recognition of
the dynamic nature of the discipline and the great diversity in undergraduate
computer science curricula, this book includes comprehensive coverage of
enough topics to make it appropriate for other courses as well. For example,
you can use this book in courses such as introductory data structures or
advanced programming and problem solving. The goal remains to give stu-
dents a superior foundation in data abstraction, object-oriented programming,
and other modern problem-solving techniques.
Linked List: The node class for linked lists has been simplified. The implemen-
tation now assumes the node class is package access only, and the other classes in
the same package have direct access to the data within a node. Students are asked
to explore the implications of making the data private in a node as an exercise.
Updates the Use of the Java Collections Framework: The Java Collections
Framework is discussed throughout the text, with a section added to show the JFC
classes that parallel those presented in the text. The Deque class, added in Java 6, is
presented in Chapter 8.
TO THE STUDENT
Thousands of students before you have read and learned from Walls and Mirrors.
The walls and mirrors in the title represent two fundamental problem-solving
techniques that appear throughout the book. Data abstraction isolates and hides
the implementation details of a module from the rest of the program, much as a
wall can isolate and hide you from your neighbor. Recursion is a repetitive tech-
nique that solves a problem by solving smaller problems of exactly the same type,
much as mirror images that grow smaller with each reflection.
This book was written with you in mind. As former college students, and as
educators who are constantly learning, we appreciate the importance of a clear
presentation. Our goal is to make this book as understandable as possible. To
help you learn and to review for exams, we have included such learning aids as
margin notes, chapter summaries, self-test exercises with answers, and a glossary.
As a help during programming, you will find Java reference materials in
Chapter 1, and inside the covers. You should review the list of this book’s fea-
tures given later in this preface under the section “Pedagogical Features.”
The presentation makes some basic assumptions about your knowledge of
Java as reviewed in Chapter 1. Some of you may need to review this language
or learn it for the first time by consulting this chapter. Others will find that
they already know most of the constructs presented in Chapter 1. You will
need to know about the selection statements if and switch; the iteration
statements for, while, and do; classes, methods, and arguments; arrays;
strings; and files. In addition to the material in Chapter 1, this book discusses
advanced Java topics such as generics and iterators in Chapter 9. We assume no
experience with recursive methods, which are included in Chapters 3 and 6.
Preface 17
All of the Java source code that appears in this book is available for your
use. Later in this preface, the description of supplementary materials explains
how to obtain these files. See page 21—Supplemental Materials—for instruc-
tions on how to access these files.
TO THE INSTRUCTOR
This edition of Walls and Mirrors uses Java 6 to enhance its emphasis on data
abstraction and data structures. The book carefully accounts for the strengths
and weaknesses of the Java language and remains committed to a pedagogical
approach that makes the material accessible to students at the introductory level.
Prerequisites
We assume that readers either know the fundamentals of Java or know another
language and have an instructor who will help them make the transition to Java.
By using Chapter 1, students without a strong Java background can quickly pick
up what they need to know to be successful in the course. In addition, the book
formally discusses Java classes. Included are the basic concepts of a class, inherit-
ance, polymorphism, interfaces, and packages. Although the book provides an
introduction to these topics in connection with the implementations of abstract
data types (ADTs) as classes, the emphasis of the book remains on the ADTs, not
on Java. The material is presented in the context of object-based programming,
but it assumes that future courses will cover object-oriented design and software
engineering in detail, so that the focus can remain on data abstraction. We do,
however, introduce the Unified Modeling Language (UML) as a design tool.
Organization
The chapters in this book are organized into two parts. In most cases, Chapters 1
through 11 will form the core of a one-semester course. Chapters 1 or 2 might
be review material for your students. The coverage given to Chapters 11
through 15 will depend on the role the course plays in your curriculum.
Flexibility
The extensive coverage of this book should provide you with the material that
you want for your course. You can select the topics you desire and present them
in an order that fits your schedule. A chapter dependency chart follows, and
shows which chapters should be covered before a given chapter can be taught.
Chapter 2
Principles Chapter 1
Java review
Chapter 4
Data abstraction
Chapter 3
Recursion
Chapter 5
Linked lists
Chapter 6
More recursion
Chapter 11
Trees
Chapter 12
Tables, priority queues
Chapter 14
Graphs Chapter 15
Chapter 13 Section on Section on
Advanced tables external tables external sorting
computer scientist can possess and is often of great value in helping one to
understand better the nature of a problem. Recursion is discussed extensively
in this chapter and again in Chapter 6 and is used throughout the book.
Included examples range from simple recursive definitions to recursive algo-
rithms for language recognition, searching, and sorting.
Chapter 4 discusses data abstraction and abstract data types (ADTs) in
detail. After a discussion of the specification and use of an ADT, the chapter
discusses Java classes, interfaces, and packages, and uses them to implement
ADTs. Chapter 5 presents additional implementation tools in its discussion of
Java reference variables and linked lists.
You can choose among the topics in Part 1 according to the background
of your students and cover these topics in several orders.
Part 2: Problem Solving with Abstract Data Types. Part 2 continues the
use of data abstraction as a problem-solving technique. Basic abstract data types
such as the stack, queue, binary tree, binary search tree, table, heap, and priority
queue are first specified and then implemented as classes. The ADTs are used in
examples and their implementations are compared.
Chapter 9 extends the treatment of Java classes by covering inheritance,
the relationships among classes, generics, and iterators. Chapter 10 formalizes
the earlier discussions of an algorithm’s efficiency by introducing order-of-
magnitude analysis and Big O notation. The chapter examines the efficiency of
several searching and sorting algorithms, including the recursive mergesort and
quicksort.
Part 2 also includes advanced topics—such as balanced search trees (2-3,
2-3-4, red-black, and AVL trees) and hashing—that are examined as table
implementations. These implementations are analyzed to determine the table
operations that each supports best.
Finally, data storage in external direct access files is considered. Mergesort
is modified to sort such data, and external hashing and B-tree indexes are used
to search it. These searching algorithms are generalizations of the internal
hashing schemes and 2-3 trees already developed.
In Part 1, you can choose among topics according to your students’ back-
ground. Three of the chapters in this part provide an extensive introduction to
data abstraction and recursion. Both topics are important, and there are
various opinions about which should be taught first. Although in this book a
chapter on recursion both precedes and follows the chapter on data abstrac-
tion, you can simply rearrange this order.
Part 2 treats topics that you can also cover in a flexible order. For exam-
ple, you can cover all or parts of Chapter 9 on advanced Java topics either
before or after you cover stacks (Chapter 7). You can cover algorithm effi-
ciency and sorting (Chapter 10) any time after Chapter 6. You can introduce
trees before queues or graphs before tables, or cover hashing, balanced search
trees, or priority queues any time after tables and in any order. You also can
cover external methods (Chapter 15) earlier in the course. For example, you
can cover external sorting after you cover mergesort in Chapter 10.
20 Preface
Data Abstraction
The design and use of abstract data types (ADTs) permeate this book’s
problem-solving approach. Several examples demonstrate how to design an
ADT as part of the overall design of a solution. All ADTs are first specified—in
both English and pseudocode—and then used in simple applications before
implementation issues are considered. The distinction between an ADT and
the data structure that implements it remains in the forefront throughout the
discussion. The book explains both encapsulation and Java classes early. Stu-
dents see how Java classes hide an implementation’s data structure from the
client of the ADT. Abstract data types such as lists, stacks, queues, trees, tables,
heaps, and priority queues form the basis of our discussions.
Problem Solving
This book helps students learn to integrate problem-solving and program-
ming abilities by emphasizing both the thought processes and the techniques
that computer scientists use. Learning how a computer scientist develops, ana-
lyzes, and implements a solution is just as important as learning the mechanics
of the algorithm; a cookbook approach to the material is insufficient.
The presentation includes analytical techniques for the development of
solutions within the context of example problems. Abstraction, the successive
refinement of both algorithms and data structures, and recursion are used to
design solutions to problems throughout the book.
Java references and linked list processing are introduced early and used
in building data structures. The book also introduces at an elementary level
the order-of-magnitude analysis of algorithms. This approach allows the
consideration—first at an informal level, and then more quantitatively—of
the advantages and disadvantages of array-based and reference-based data
structures. An emphasis on the trade-offs among potential solutions and
implementations is a central problem-solving theme.
Finally, programming style, documentation including preconditions and
postconditions, debugging aids, and loop invariants are important parts of the
problem-solving methodology used to implement and verify solutions. These
topics are covered throughout the book.
Applications
Classic application areas arise in the context of the major topics of this book.
For example, the binary search, quicksort, and mergesort algorithms provide
important applications of recursion and introduce order-of-magnitude analy-
sis. Such topics as balanced search trees, hashing, and file indexing continue
the discussion of searching. Searching and sorting are considered again in the
context of external files.
Algorithms for recognizing and evaluating algebraic expressions are first
introduced in the context of recursion and are considered again later as an
Preface 21
Pedagogical Features
The pedagogical features and organization of this book were carefully
designed to facilitate learning and to allow instructors to tailor the material
easily to a particular course. This book contains the following features that
help students not only during their first reading of the material, but also
during subsequent review:
Chapter outlines and previews
Key Concepts boxes
Margin notes
Chapter summaries
Cautionary warnings about common errors and misconceptions
Self-test exercises with answers
Chapter exercises and programming problems. The most challenging exer-
cises are labeled with asterisks. Answers to the exercises appear in the
Instructor’s Resource Manual.
Specifications for all major ADTs in both English and pseudocode
Java class definitions for all major ADTs
Examples that illustrate the role of ADTs in the problem-solving process
Appendixes, including a review of Java
Glossary of terms
SUPPLEMENTAL MATERIALS
The following supplementary materials are available online to all readers of this
book at www.pearsonhighered.com/cssupport.
Source code of all the Java classes, methods, and programs that appear in
the book
Errata: We have tried not to make mistakes, but mistakes are inevitable. A
list of detected errors is available and updated as necessary. You are invited
to contribute your finds.
22 Preface
TALK TO US
This book continues to evolve. Your comments, suggestions, and correc-
tions will be greatly appreciated. You can contact us through the publisher at
[email protected], or:
ACKNOWLEDGMENTS
The suggestions from outstanding reviewers have, through the past few editions,
contributed greatly to this book’s present form. In alphabetical order, they are:
Ronald Alferez—University of California at Santa Barbara
Claude W. Anderson—Rose-Hulman Institute of Technology
Don Bailey—Carleton University
N. Dwight Barnette—Virginia Tech
Jack Beidler—University of Scranton
Elizabeth Sugar Boese—Colorado State University
Debra Burhans—Canisius College
Tom Capaul—Eastern Washington University
Eleanor Boyle Chlan—Johns Hopkins University
Chakib Chraibi—Barry University
Jack N. Donato—Jefferson Community College
Susan Gauch—University of Kansas
Mark Holliday—Western Carolina University
Lily Hou—SUN Microsystems, Inc.
Helen H. Hu—Westminster College
Lester I. McCann—The University of Arizona
Rameen Mohammadi—SUNY, Oswego
Narayan Murthy—Pace University
Thaddeus F. Pawlicki—University of Rochester
Preface 23
Problem-Solving
Techniques
Review of Java
Fundamentals
Comments
A variety of com- Each comment line in Java begins with two slashes (//) and continues until the
menting styles are end of the line. You can also begin a multiple-line comment with the characters
available in Java /* and end it with */. Although the programs in this book do not use /* and */,
it is a good idea to use this notation during debugging. That is, to isolate an
error, you can temporarily ignore a portion of a program by enclosing it within
/* and */. However, a comment that begins with /* and ends with */ cannot
contain another comment that begins with /* and ends with */. Java also has a
third kind of comment that is used to generate documentation automatically
using javadoc, a documentation utility available in the Software Development
Kit (SDK). This comment uses a /** to start and a */ to end.
Variables
A variable contains A variable, whose name is a Java identifier, represents a memory location that
either the value of a contains a value of a primitive data type or a reference. You declare a variable’s
primitive data type data type by preceding the variable name with the data type, as in
or a reference to an
object
double radius; // radius of a sphere
String name; // reference to a String object
Note that the second declaration does not create a String object, only a vari-
able that stores the location of a String object. You must use the new operator
to create a new object.
Language Basics 29
double radius;
double radiusCubed;
Some of the data types are available in two forms and sizes. Figure 1-1 lists
the available primitive data types.
A boolean value can be either true or false. You represent characters by
enclosing them in single quotes or by providing their Unicode integer value
(see Appendix B). Integer values are signed and allow numbers such as –5 and
+98. The floating-point types provide for real numbers that have both an
integer portion and a fractional portion. Character and integer types are called
integral types. Integral and floating-point types are called arithmetic types.
A value of a primitive type is not considered to be an object and thus
cannot be used in situations where an object type is expected. For this reason,
the package java.lang provides corresponding wrapper classes for each of A wrapper class is
the primitive types. Figure 1-1 also lists the wrapper class corresponding to available for each
each of the primitive types. primitive data type
Each of these classes provides a constructor to convert a value of a primi-
tive type to an object when necessary. Once such an object has been created,
the value contained within the object cannot be modified. Here is a simple
example involving integers:
FIGURE 1-1
The class Integer has a method intValue that retrieves the value stored
in an Integer object. Classes corresponding to the other primitive types
provide methods with similar functionality.
Java has a feature called autoboxing that makes it easier to convert from a
primitive type to their equivalent wrapper class counterparts. In the previous
example, we explicitly created a new Integer object to store the value 9. With
autoboxing, we can simply write
Integer intObject = 9;
The compiler automatically adds the code to convert the integer value into the
proper class (Integer in this example).
The reverse process of converting an object of one of the wrapper
classes into a value of the corresponding primitive type is called auto-unboxing.
In the example
int x = intObject + 1;
the compiler again automatically generates the code to convert the Integer
object intObject to a primitive type (int in this example) so that the expres-
sion can be evaluated.
References
A reference variable Java has one other type, called a reference, that is used to locate an object.
contains an object’s Unlike other languages, such as C++, Java does not allow the programmer to
location in memory perform any operations on the reference value. When an object is created using
the new operator, the location of the object in memory is returned and can be
assigned to a reference variable. For example, the following line shows the ref-
erence variable name being assigned the location of a new string object:
Literal Constants
Literal constants You use literal constants to indicate particular values within a program. In the
indicate particular following expression, the 4 and 3 are examples of literal constants that are used
values within a within a computation.
program
4 * Math.PI * radiusCubed / 3
Language Basics 31
You can also use a literal constant to initialize the value of a variable. For exam-
ple, you use true and false as the values of a boolean variable, as we men-
tioned previously.
You write decimal integer constants without commas, decimal points, or
leading zeros.1 The default data type of such a constant is either int, if small Do not begin a
enough, or long. decimal integer
You write floating constants, which have a default type of double, with a constant with zero
decimal point. You can specify an optional power-of-10 multiplier by writing e
or E followed by the power of 10. For example, 1.2e-3 means 1.2 × 10–3.
Character constants are enclosed in single quotes—for example, 'A' and
'2'—and have a default type of char. You write a literal character string as a
sequence of characters enclosed in double quotes.
Several characters have names that use a backslash notation, as given in
Figure 1-2. This notation is useful when you want to embed one of these char-
acters within a literal character string. For example, the statement
uses the new-line character \n to place a new-line character after the string
Hello. You will learn about this use of \n in the discussion of output later in this
chapter. You also use the backslash notation to specify either a single quote as a
character constant ( \') or a double quote ( \") within a character string.
Named Constants
Unlike variables, whose values can change during program execution, named
constants have values that do not change. The declaration of a named con- The value of a
stant is like that of a variable, but the keyword final precedes the data type. named constant
For example, does not change
Constant Name
\n New line
\t Tab
\' Single quote
\" Double quote
\0 Zero
FIGURE 1-2
Some special character constants
1. Octal and hexadecimal constants are also available, but they are not used in this
book. An octal constant begins with 0, a hex constant with 0x or 0X.
32 Chapter 1 Review of Java Fundamentals
Operators have a The operators *, /, and % have the same precedence,2 which is higher than that
set precedence of + and -; unary operators3 have a higher precedence than binary operators.
The following examples demonstrate operator precedence:
a - b / c means a - (b / c) ( precedence of / over -)
2. A list of all Java operators and their precedences appears inside the back cover of this
book.
3. A unary operator requires only one operand, for example, the - in -5. A binary
operator requires two operands, for example, the + in 2 + 3.
Language Basics 33
a / b * c Operators are
either left- or right-
means associative
(a / b) * c
The assignment operator and all unary operators are right-associative, as you
will see later. You can use parentheses to override operator precedence and
associativity.
Relational and logical expressions. You can combine variables and con-
stants with parentheses; with the relational, or comparison, operators <, <=,
>=, and >; and with the equality operators == (equal to) and != (not equal to)
to form a relational expression. Such an expression evaluates to false if the
specified relation is false and to true if it is true. For example, the expression
5 != 4 has a value of true because 5 is not equal to 4. Note that equality
operators have a lower precedence than relational operators. Also note that the
equality operators work correctly only with the primitive types and references. Equality operators
The == operator determines only whether two reference variables are referenc- work correctly only
ing the same object, but not whether two objects are equal. with primitive types
and references
You can combine variables and constants of the arithmetic types, rela-
tional expressions, and the logical operators && (and) and || (or) to form
logical expressions, which evaluate to false if false and to true if true. Java Logical expressions
evaluates logical expressions from left to right and stops as soon as the value of are evaluated from
the entire expression is apparent; that is, Java uses short-circuit evaluation. left to right
For example, Java determines the value of each of the following expressions Sometimes the
without evaluating (a < b): value of a logical
expression is
apparent before it
(5 == 4) && (a < b) // false since (5 == 4) is false is completely
(5 == 5) || (a < b) // true since (5 == 5) is true examined
Implicit type conversions for the primitive numeric types. Automatic con- Conversions from
versions from one numeric data type to another can occur during assignment one data type to
and during expression evaluation. For assignments, the data type of the expres- another occur
during both assign-
sion on the right-hand side of the assignment operator is converted to the data ment and expres-
type of the item on the left-hand side just before the assignment occurs. Float- sion evaluation
ing-point values are truncated—not rounded—when they are converted to
integral values.
During the evaluation of an expression, any values of type byte, char, or
short are converted to int. These conversions are called integral promo-
tions. After these conversions, if the operands of an operator differ in data
type, the data type that is lower in the following hierarchy is converted to one
that is higher (int is lowest):
For example, if A is long and B is float, A + B is float. A copy of A’s long value
is converted to float prior to the addition; the value stored at A is unchanged.
Other operators, such as -=, *=, /=, and %=, have analogous meanings.
The operators ++ Two more operators, ++ and --, provide convenient incrementing and
and -- are useful decrementing operations:
for incrementing
and decrementing ++a means a += 1, which means a = a + 1
a variable
Similarly,
--a means a -= 1, which means a = a - 1
The operators ++ and -- can either precede their operands, as you just saw, or
follow them. Although a++, for instance, has the same effect as ++a, the results
differ when the operations are combined with assignment. For example,
b = ++a means a = a + 1; b = a
Here, the ++ operator acts on a before the assignment to b of a’s new value. In
contrast,
b = a++ means b = a; a = a + 1
The assignment operator assigns a’s old value to b before the ++ operator acts
on a. That is, the ++ operator acts on a after the assignment. The operators ++
Language Basics 35
and -- are often used within loops and with array indexes, as you will see later
in this chapter.
In addition to the operators described here, Java provides several other
operators. A summary of all Java operators and their precedences appears
inside the back cover of this book.
Arrays
An array is a collection of elements, items, or values that have the same data An array is a collec-
type. Array elements have an order: An array has a first element, a second ele- tion of data that has
ment, and so on, as well as a last element. That is, an array contains a finite, the same type
limited number of elements. Like objects, an array does not come into exist-
ence until it is allocated using the new statement. At that time, you specify the
desired size of the array. Because you can access the array elements directly and You can access
in any order, an array is a direct access, or random access, data structure. array elements
directly and in
any order
One-dimensional arrays. When you decide to use an array in your pro-
gram, you must declare it and, in doing so, indicate the data type of its ele-
ments. The following statements declare a one-dimensional array, maxTemps,
which contains the daily maximum temperatures for a given week:
The bracket notation [] declares maxTemps as an array. The array is then allo-
cated memory for seven floating-point elements.
The declared length of an array is accessible using the data field length
associated with the array. For example, maxTemps.length is 7. You can refer Use an index to
to any of the floating-point elements in maxTemps directly by using an specify a particular
element in an array
expression, which is called the index, or subscript, enclosed in square brack-
ets. In Java, array indexes must have integer values in the range 0 to length An array index has
– 1, where length is the data field just described. The indexes for maxTemps an integer value
range from 0 to DAYS_PER_WEEK – 1. For example, maxTemps[4] is the fifth greater than or
equal to 0
element in the array. If k is an integer variable whose value is 4, maxTemps[k]
is the fifth element in the array, and maxTemps[k+1] is the sixth element.
Also, maxTemps[++k] adds 1 to k and then uses the new value of k to index
maxTemps, whereas maxTemps[k++] accesses maxTemps[k] before adding 1
to k. Note that you use one index to refer to an element in a one-dimen-
sional array.
Figure 1-3 illustrates the array maxTemps, which at present contains only
five temperatures. The last value in the array is maxTemps[4]; the values of
maxTemps[5] and maxTemps[6] are 0.0, the default initial value for floating-
point numbers.
You can initialize the elements of an array when you declare it by specify-
ing an initializer list. The initializer list is a list of values separated by commas
and enclosed in braces. For example,
36 Chapter 1 Review of Java Fundamentals
0 1 2 3 4 5 6 Index
FIGURE 1-3
A one-dimensional array of at most seven elements
You can initialize an double [] weekDayTemps = {82.0, 71.5, 61.8, 75.0, 88.3};
array when you
declare it
initializes the array weekDayTemps to have five elements with the values listed.
Thus, weekDayTemps[0] is 82.0, weekDayTemps[1] is 71.5, and so on.
You can also declare an array of object references. The declaration is
similar to that of an array of primitive types. Here is a declaration of an array
for ten String references:
Note that all of the references will have the initial value null until actual
String objects are created for them to reference. The following statement
creates a String object for the first element of the array:
These statements specify the ranges for two indexes: The first index can range
from 0 to 6, while the second index can range from 0 to 51. Most people picture
a two-dimensional array as a rectangular arrangement, or matrix, of elements
Language Basics 37
Columns
0 1 51
Rows
FIGURE 1-4
A two-dimensional array
that form rows and columns, as Figure 1-4 indicates. The first dimension given
in the definition of minTemps is the number of rows. Thus, minTemps has 7 rows
and 52 columns. Each column in this matrix represents the seven daily minimum
temperatures for a particular week.
To reference an element in a two-dimensional array, you must indicate both In a two-dimensional
the row and the column that contain the element. You make these indications of array, the first
row and column by writing two indexes, each enclosed in brackets. For example, index represents
the row, the second
minTemps[1][51] is the element in the 2nd row and the 52nd column. In the index represents the
context of the temperature example, this element is the minimum temperature column
recorded for the 2nd day (Monday) of the 52nd week. The rules for the indexes of
a one-dimensional array also apply to the indexes of multidimensional arrays.
As an example of how to use a two-dimensional array in a program, con-
sider the following program segment, which determines the smallest value in
the previously described array minTemps:
int[][] x = {{1,2,3},{4,5,6}};
That is, the statement initializes the elements x[0][0], x[0][1], x[0][2],
x[1][0], x[1][1], and x[1][2] in that order. In general, when you assign
initial values to a multidimensional array, it is the last, or rightmost, index that
increases the fastest.
The if Statement
You can write an if statement in one of two ways:
or
if (expression)
statement1
else
statement2
where statement1 and statement2 represent any Java statement. Such statements can be
compound; a compound statement, or block, is a sequence of statements enclosed
in braces. Though not a requirement of Java, this text will always use a compound
statement in language constructs, even if only a single statement is required.
If the value of expression is true, statement1 is executed. Otherwise, the
first form of the if statement does nothing, whereas the second form executes Parentheses around
statement2. Note that the parentheses around expression are required. the expression in
For example, the following if statements each compare the values of two an if statement
are required
integer variables a and b:
if (a > b) {
System.out.println(a + " is larger than " + b + ".");
} // end if
System.out.println("This statement is always executed.");
if (a > b) {
larger = a;
System.out.println(a + " is larger than " + b + ".");
}
else {
larger = b;
System.out.println(b + " is larger than " + a + ".");
} // end if
You can nest if statements in several ways, since either statement1 or statement2
can itself be an if statement. The following example, which determines the largest
of three integer variables a, b, and c, shows a common way to nest if statements:
// except February
case 2: // assume leapYear is true if leap
// year, else is false
if (leapYear) {
daysInMonth = 29;
}
else {
daysInMonth = 28;
} // end if
break;
default:
System.out.println("Incorrect value for Month.");
} // end switch
Iteration Statements 41
case expression:
int sum = 0;
int index = 0;
while (index <= myArray.length) {
sum += myArray[index];
} // end while
The break and continue statements. You can use the break statement—
Use of a break
which you saw earlier within a switch statement—within any of the iteration state- statement within a
ments. A break statement within the body of a loop causes the loop to exit immedi- loop is generally
ately. Execution continues with the statement that follows the loop. This use of poor style
break within a while, for, or do statement is generally considered poor style.
42 Chapter 1 Review of Java Fundamentals
The continue statement stops only the current iteration of the loop and
begins the next iteration at the top of the loop. The continue statement is
valid only within while, for, or do statements.
int sum = 0;
for (int counter = 1; counter <= n; ++counter) {
sum += counter;
} // end for
If n is less than 1, the for statement does not execute at all. Thus, the previous
statements are equivalent to the following while loop:
int sum = 0;
int counter = 1;
while (counter <= n) {
sum += counter;
++counter;
} // end while
// this statement is always executed
int x = 0;
The initialize and update portions of a for statement each can contain
several expressions separated by commas, thus performing more than one
action. For example, the following loop raises a floating-point value to an
integer power by using multiplication:
Both power and expon are assigned values before the body of the loop exe-
cutes for the first time.
Because the for statement consolidates the initialization, testing, and A for statement is
updating steps of a loop into one statement, Java programmers tend to favor it usually favored over
over the while statement. For example, notice how the following while loop the while statement
sums the values in an array x:
sum = 0;
int i = 0;
while (i < x.length) {
sum += x[i];
i++;
} // end while
You can omit any You can omit any of the expressions initialize, test, or update from a for
of the initialization, statement, but you cannot omit the semicolons. For example, you can move
testing, and updat- the update step from the previous for statement to the body of the loop:
ing steps in a for
statement, but you
cannot omit the for (int i = 0, sum = 0; i < x.length; ) {
semicolons sum += x[i++];
} // end for
You also could omit both the initialization and the update steps, as in the fol-
lowing loop:
for ( ; x > 0; ) {
statements to process nextValue in inputLine
} // end for
while (x > 0)
Although you can omit the test expression from for, you probably will not
want to do so, because then the loop would be infinite.
The for loop and arrays. Java provides a loop construct that simplifies iter-
ation through the elements of an array. A logical name for this loop construct
would be the “foreach” loop, but the language developers wanted to avoid
adding a new keyword to the language. So the new form of the for loop is
often referred to as the “enhanced for loop.”
The syntax for the enhanced for loop when used with arrays is as follows:
where ArrayElementType is the type of each element in the array, and arrayName
is the name of the array you wish to process element by element. The loop
begins with the variableName assigned the first element in the array. With each
iteration of the loop, variableName is associated with the next element in the
array. This continues until all of the elements in the array have been processed.
For example:
The do Statement
Use the do statement when you want to execute a loop at least once. Its
general form is
do { A do statement
statement loops at least once
} while (expression);
char response;
do {
. . . (a sequence of statements)
ask the user if they want to do it again
store user’s response in response
} while ( (response == 'Y') || (response == 'y') );
This application includes all of the basic elements of Java program struc-
ture (packages, classes, data fields, and methods). The sections that follow
discuss each of these elements.
46 Chapter 1 Review of Java Fundamentals
File SimpleSphere.java
1. Indicates SimpleSphere is part of a package ----> package MyPackage;
2. Indicates class Math is used by SimpleSphere --> import java.lang.Math;
3. Begins class SimpleSphere --------------------------> public class SimpleSphere {
4. Declares a private data field radius -----------------> private double radius;
5. Declares a constant ---------------------------------------> public static final double DEFAULT_RADIUS = 1.0;
6. A default constructor ------------------------------------> public SimpleSphere() {
7. Assignment statement ----------------------------------> radius = DEFAULT_RADIUS;
} // end default constructor
8. A second constructor ------------------------------------> public SimpleSphere(double initialRadius) {
9. Assignment statement -----------------------------------> radius = initialRadius;
} // end constructor
10. Begins method getRadius ---------------------------> public double getRadius() {
11. Returns data field radius -----------------------------> return radius;
} // end getRadius
12. Begins method getVolume ---------------------------> public double getVolume() {
13. A comment -------------------------------------------------> // Computes the volume of the sphere.
14. Declares and assigns a local variable ------------------> double radiusCubed = radius * radius * radius;
15. Returns result of computation -------------------------> return 4 * Math.PI * radiusCubed / 3;
} // end getVolume
16. Ends class SimpleSphere ----------------------------> } // end SimpleSphere
File TestClass.java
17. Indicates TestClass is part of a package ---------> package MyPackage;
18. Begins class TestClass -------------------------------> public class TestClass {
19. Begins method main -----------------------------------> static public void main(String[] args) {
20. Declares reference ball --------------------------------> SimpleSphere ball;
21. Creates a SimpleSphere object --------------------> ball = new SimpleSphere(19.1);
22. Outputs results --------------------------------------------> System.out.println("The volume of a sphere of radius "
23. Continuation of output string --------------------------> + ball.getRadius() + " inches is "
24. Continuation of output string --------------------------> + (float)ball.getVolume()
+ "cubic inches\n");
} //end main
25. Ends class TestClass ----------------------------------> } // end TestClass
FIGURE 1-5
Packages
Java packages provide a mechanism for grouping related classes. To indicate
that a class is part of a package, you include a package statement as the first
program line of your code. For example, lines 1 and 17 in Figure 1-5 indicate
Program Structure 47
that both of these classes, SimpleSphere and TestClass, are in the package
MyPackage. The format of the package statement is
To include a class in
package package-name; a package, begin
the class’s source
Java assumes that all of the classes in a particular package are contained in the file with a package
statement
same directory. Furthermore, this directory must have the same name as the package.
The Java API actually consists of many predefined packages. Some of the Place the files that
more common of these packages are java.lang, java.util, and java.io. contain a package’s
The dot notation in these package names directly relates to the directory struc- classes in the same
directory
ture containing these packages. In this case, all of the directories correspond-
ing to these packages are contained in a parent directory called java.
import statement. The import statement allows you to use classes con-
tained in other packages. The format of the import statement is as follows:
import java.lang.*;
In this case, the * indicates that all of the items from the package
java.lang should be imported. Actually, this particular line can be omitted
from the program, since java.lang is implicitly imported to all Java code.
Explicitly importing java.lang.Math makes it clear to others who read your
code that you are using the class Math in this code.
Classes
An object in Java is an instance of a class. You can think of a class as a data type that An object is an
specifies the data and methods that are available for instances of the class. A class instance of a class
definition includes an optional subclassing modifier, an optional access modifier, A Java class defines
the keyword class, an optional extends clause, an optional implements clause, a new data type
and a class body. Figure 1-6 describes each of the components of a class.
When a new class is created in Java, it is either specifically made a subclass
of another class through the use of the extends clause or it is implicitly a sub-
class of the Java class Object. Creating a subclass is known as inheritance and
is discussed briefly in Chapter 4 and in depth in Chapter 9 of this text.
To create an object or instance of a class, you use the new operator. For
example, the expression
new SimpleSphere()
Class body Enclosed in braces Contains data fields and methods for the class.
FIGURE 1-6
Components of a class
Now let’s briefly examine the contents of the class body: data fields and
methods.
Data Fields
Data fields are class members that are either variables or constants. Data field
declarations can contain modifiers that control the availability of the data field
(access modifiers) or that modify the way the data field can be used (use modi-
fiers). The access modifiers are effective only if the class is declared public.
Although this text uses only a subset of the modifiers, Figure 1-7 shows them
all for completeness.
Program Structure 49
Access modifier public Data field is available everywhere (when the class is
(use only one) also declared public).
Use modifiers static Indicates that only one such data field is available
(all can be used at for all instances of this class. Without this modifier,
once) each instance has its own copy of a data field.
FIGURE 1-7
Data fields are typically declared private or protected within a class, with A class’s data fields
access provided by methods in the class. Hence, a method within a class has should be private
access to all of the data fields declared in the class. This allows the developer of or protected
the class to maintain control over how the data stored within the class is used.
Other documents randomly have
different content
What a sense of deep peace and security and privacy there was in
the two being thus free to talk together of life and the world—in that
womanless house! No woman sitting beside the fire to interject
herself and pull things her way; or to sit by without a sign—and pull
things her way afterwards—without a sign.
The physical comfort of the night, and the rain, and the snug
hearth awoke a desire for more confidences.
"Tell me about the medical schools when you were a student. Not
about the professors. I don't want to hear anything about the
professors. You wouldn't know anything about them, anyhow: no
student ever does. But what were the students up to among
themselves at nights? The wild ones. I don't want to hear anything
about the goody-goody ones. Tell me about the devils—the worst of
the devils."
"You!"
There was a mild wave of the hand by the historian of the night,
much as one puts aside a faded wreath, deprecating being crowned
with it a second time.
"Somehow I feel," said the younger of the men, "that there have
been great men all about here. I don't see any now; but I have a
feeling that they have been here—great men. I feel them behind me
—all kinds of great men. It is like the licks where we now find the
footprints and the bones of big game, larger animals that have
vanished. There are the bones of greater men in Kentucky: I feel
their lives behind me."
"They are behind you: the earth is rank with them. You need not
look anywhere else for examples. I don't know how far you got in
your Homer at school before you were tired of it; but there is the
Iliad of Kentucky: I am glad you have begun to read that!"
The rain on the shingles and in the gutters began to sound like
music. The two men alone there in their talk about life, not a woman
near, a kind of ragged sublimity.
"Tell me about the professions in the War: what did they do about
it; how did they act?"
The young hunter quietly got up and lit his candle and squared
himself in the middle of the floor, pale with the sacred fire of a
youth's ideal.
He rose from his chair and tapped the ash out of his
meerschaum. Through force of habit and old association with the
race-course he looked at his timepiece.
"I win that race in good time," he said. "That colt was hard to
manage, obstreperous and balky."
It had always been his secret wish that his nephew would enter
the profession that he himself had spurned. Perhaps no man ever
ceases to have some fondness for the profession he has declined, as
perhaps a woman will to the last send some kind thoughts toward
the man she has rejected.
And now eight years followed, during which the youth Downs
Birney became young Dr. Birney—a very great stage of actual
progress. Seven away from Kentucky, and one there since his return.
Of those seven, five in New York for a degree; and two in Europe—in
Berlin, in Vienna—for more lectures, more hospital work, another
degree. At the end of the second he returned incredibly developed
to Kentucky, to the manor house and the stock farm; and to the
uncle to whom these years had furnished abundance of means
whereby to get the best of all that was wisely to be gotten: an
affectionate abundance, no overfond super-abundance, no
sentimentality: merely a quiet Kentucky sun throwing the energy of
its rays along that young life-track—hanging out a purse of gold at
each quarter-stretch, to be snatched as the thoroughbred passed.
So he was clueless. He must make his own clues and then follow.
Nor could there be any dallying, since he could not hope to succeed
in his profession as a young unmarried physician: thus pressure from
without equalled pressure from within.
But while they could not abet him in the error of thinking that he
had returned a cosmopolitan, bringing high prestige, instantly they
showed general excitement that he—one of themselves—was at
home again in search of a wife. He had arrived like a starving bee
released in a ripe vineyard; and for a while he could only whirl
about, distracted by indecision as to what cluster of grapes he
should settle on: not that the grapes did not have something to say
as to the privilege of alighting. After the bee had selected the bunch,
the bunch selected the bee. A vineyard ripe to be gathered—and
being gathered! Every month or so a vine disappeared—claimed for
Love's vintage—stored away in Love's cellar.
His partner that afternoon was his hostess—a Kentucky girl just
home from her Northern college as a graduate. She too had been
away for several years; and they had this in common as the first
bond—that they had arrived as comparative strangers and saw their
home surroundings from the outside: they spoke of it: it introduced
them.
There was tension in the play for this reason; and for others: this
first public appearance with so much going on in imagination and
sympathy. Too great tension developed as the battle of the racquets
went on: so that the doctor's partner, overreaching and twisting,
sprained an ankle, and the games ended for them: she was assisted
upstairs, and he applied his skill and his treatment.
As he drove home he thought a good deal of his partner: of her
proud reserve toward him out of the game and of her inseparable
blending of herself with him in the game; her devotion to their
common cause; her will not that she should win but that both should
win; her unruffled ignoring of a bad play of his or a bad play of her
own; the freshened energy of her attack after a reverse; her matter-
of-course pleasure when he played well or when she played well; the
complete surrender of herself to him for the game—after which
instantly there was nothing between them except the courtesy of a
hostess. He thought of these traits. And then he recalled her
fortitude during the acute suffering with that twisted ankle! How
contemptuously she had borne pain!
But at the end of his first year the doctor felt that he had made
only a general advance toward the long battle-line of Love; he had
reconnoitred, but he had not attacked; he had a vast marital
receptivity embracing many square miles. He had slid his hands
along the nuptial rope, but he could not as yet discover who was
waiting beside the bridal knot.
He had never met the girl that his friend was to marry: her home
was in another neighborhood, and the demands of this first year
upon him had been too many. He had not even had time to go to
the wedding. Now he checked his horse in order not to pass the
carriage, and at a respectful distance of a few yards constituted
himself its happy procession. At the front gate it turned in and rolled
through the woods to the house, the windows of which were blazing
with candles—bridal lights and the lights of Christmas Eve! He
stopped at the gate and followed the progress of it as it intercepted
the lights now of one window and now of another as it wound along
the drive. Leaning forward with his forearms on his knees and
peering from the side-curtain, he saw the front doors thrown open,
or knew this by the flood of radiance that issued from the hall; saw
the young master of the house walk to the top step of his porch and
there turn and wait to receive his bride—in true poetic and royal and
manly fashion: wishing her to come to him as he faced her on his
threshold; he saw arms outstretched toward her, saw her mount
falteringly and give her hands; and saw them walk side by side into
the hall: the servants closed in upon them, the doors closed upon
the servants.
"Dr. Birney, there is a young man in this buggy who needs your
best attention: see that he gets it and gets it quickly."
"If anything should happen before you are able to reach me,
these few words will be my last.
"You will find that everything of value I possess has been left to
you. You think I have loved horses; I have loved nothing but you. I
have loved you because you were worthy of it; but I should have
loved you if you had not been worthy. The horses meant a good deal
to me in life, but they mean nothing in death.
"I believe you will be one more great Kentucky country doctor.
And whatever race you may have to run in this world, whether you
win or whether you lose, I know it will be a hard, a gallant, struggle:
that is all the thoroughbred can ever do. Having delivered over to
you everything I own and retaining only the things I cannot will
away,—my judgment, my confidence in you, and my devotion to
you,—I wager these that you will win life's race and win it gloriously.
My last bet—with my last coin—you will win!
The doctor rushed out to the porch, and young Ousley spurred his
horse up to the side of it, riding over flower-beds, trampling and
ruining plants that happened not now to be in bloom. The two
friends after a long crushing grip poured out their friendship with
eye and speech, greeting and laughter.
They talked rapidly of many things. Then the object of the visit
was disclosed—with an altered voice and manner:—
"As soon as you have had breakfast, Downs, I wish you would
come over. Mrs. Ousley is not very well. She would like to see you."
A new look had come into his eyes: he stood as on the peak of
experience—the true mountain-top of the life of this world.
The young husband rode back to the porch, wiping the snow out
of his laughing eyes: they looked blue as with the clear laughter of
the sky.
"That will never do!" he said with a backward motion of his head
toward the solitary chair at the breakfast-table. "What right have you
to defraud a girl out of all that happiness?"
"I am not defrauding a girl out of all that happiness: I am being
defrauded. I am not the culprit: I am the victim. As a consequence
of trying to save the lives of other husbands, I have nearly come to
my own death as a bachelor: I have about succumbed to inanition: I
am a mere Hamlet of soliloquy—and abstention."
"Mrs. Ousley would like to see you as soon as you can come,
doctor."
"Thank you."
"Thank you!"
As Dr. Birney poured out his coffee and buttered his biscuit, he
said to himself that now the bread of life was being buttered.
What he had been looking for it seemed to him that he had found
too late in Josephine Ousley. Had he found her before her marriage,
he would have looked at no other, nor have wavered a year. The
actual significance of this was that he had encountered one of the
persistent dreams of mankind—the dream of ideal love and ideal
marriage with one who is unattainable.
The history of the race, of its art, of its literature, has borne
through ages testimony to the vividness and to the tyranny of this
obsession, this mistake, or this truth which may be one of Nature's
deepest. For it may be error and it may be truth, or sometimes the
one and sometimes the other. It may be one of the vast forces in
Nature which we are but now beginning to observe—one of her
instincts of intuitive selection which announces itself instantly and is
never to be reversed: such an instinct as governs the mating of
other lives not human. But there it is in our own species for us to
make out of it what we can. There are men who for the rest of their
lives look back upon the mere sight of some woman, a solitary brief
meeting with her, as though that were their natural and perfect
union. There are women who are haunted by the same influence
and allegiance to some man—seen once—perhaps never seen at all
except in a picture. Among the dreams of humanity about ideal
strength, ideal wisdom, ideal justice and charity and friendship, this
must be set apart as its dream of ideal love; and as all high and
beautiful dreams about human nature are welcome, provided only
we never awaken from them, let those who dream thus dream on.
But the tragedy of it falls upon those who in actual life practically
supplant the imagined. Let Petrarch dream of Laura, let Dante dream
of Beatrice, if only the perfections of Laura and Beatrice do not come
into judgment against the actual wives of Petrarchs and Dantes. Let
the ideal love of Romeo and Juliet gladden mankind only as a dream
of the unfulfilled.
Dr. Birney had fallen under the influence of this error, or this
truth: the bride of his friend instantly filled his imagination as that
vision of perfection which dreams alone bring to visit us. He was not
yet in love with her, not a feeling of his nature had yet made its start
towards her: but she had declared herself as for him the ideal
woman—ensphered in the unattainable. As proof of this she released
in him from the hour of his meeting her finer things than he had
been aware of in his own nature: her countenance, her form, her
voice, her whole presence, her spirit, disclosed for him for the first
time the whole glory and splendor of human life and of a man's
union with a woman.
As he tried to withdraw his mind from this belief and fix it upon
his own separate future, he discovered that his outlook was no
longer single nor clear. Something stood in his path—an irremovable
obstacle. Sometimes in sleep we try to drive around an obstruction
in our road, and as often as we drive around it it reappears where it
was before: such an obstruction had obtruded itself across his
progress.
He was with Mrs. Ousley when her child was born—he saved her
life and the child's life and his friend's happiness. And in response he
found that both of them were now drawing him into that closer
friendship which rests upon danger shared and passed—upon
respect and power.
The first day that Mrs. Ousley sat in her drawing-room with her
infant across her knees the doctor was there; and as he studied the
perfect group—husband and wife and child—it seemed to him that
behind them should have shone the full-orbed golden splendor of
this life's ideal happiness.
She gave him a quick startled look, thinking not of him, but with a
woman's intuitive forecast sending her sympathy and apprehension
on into the life of another woman.
About a year later there reached Dr. Birney one morning a piece
of evidence as to how his reputation was spreading: from another
neighborhood a farmer of small means rode to his door and
besought him to come and see a member of his family: this request
implied that the regular family physician had been passed over,
supplanted; and when the poor turn against their physicians and
discharge them, it is a bad sign indeed—for the physicians.
The doctor upon setting out sent his thoughts to this professional
brother who had been discredited: he would gladly have saved him
from the wound.
He pulled his horse's head into a dirt road and crossed to another
turnpike and visited his new patient and went on to another county
seat and put up his horse at a livery stable to be groomed and fed
and took his dinner at the little tavern and wandered aimlessly about
the town and started back towards sundown and reached home late
in the night and went to his rooms without awaking his wife. As he
lighted his lamp in the library under its rays he saw a note from Mrs.
Ousley to them, asking their company to supper next evening. His
wife had pencilled across the top of the page a message that she
would not go.
When the evening was over and the moment had come to leave,
she was at the side of her husband again; and under the chandelier
in the hall she suddenly looked up to it with a beautiful mystical
rapture and consecration—as if to the mistletoe of her bridal eve.
And thus it came about that the final stage of the doctor's
Progress attained dimensions large enough to contain Hogarth's
most human four: for it represented that Progress of the Rake which
sometimes in everyday reality coincides with the Progress of the
Harlot and with the Progress of Marriage à la Mode and with the
Progress of Cruelty: so that he thus achieved as much by way of
getting on as may be reasonably demanded of any plodding man.
It was an August day in this same year which was now closing its
record with the thoughtful days of December. It was afternoon, and
it was Saturday.
The hotel dinner was unusually rich that day because a great
circus and menagerie had pitched its tents in a vacant lot on the
edge of town; and there was to be an afternoon and an evening
performance, and the town was crowded.
He made his way through excited throngs to the livery stable, and
had soon started. On the way across town, above low roofs and
fences, he caught sight of weather-stained canvas tents, every
approach toward which now had its rolling tide of happy faces,
young and aged. At a cross street the hurrying people flowed so
thoughtlessly about his buggy wheels that he checked his horse lest
some too careless child might be trodden on; and as he sat there,
smiling out at them and waiting for them to pass, suddenly above
the tumult of voices with their brotherliness he heard a sound that
made him forget his surroundings—forget human kinship—and think
only of another kinship of his to something secret and undeclared: in
one of the tents a great lonely beast lifted its voice and roared out
its deep jungle-cry. The primitive music rang above the civilized
swarm like a battle-challenge uttered from the heart of Nature—that
sad long trumpet call of instinct—caged and defrauded; a majestic
despair for things within that could never change and for things
without that were never to be enjoyed. Shallow and pitiable by
comparison sounded the human voices about the buggy wheels.
"To make one outcry like that!—sincere, free! But to be heard
once—but to be understood at last!" said the doctor.
It was not long before he saw his own carriage approaching; and
his children, recognizing him, sprang to their feet and waved
tumultuously. As the vehicles drew alongside, he looked at them
rather absent-mindedly:—
"Well, as for me," cried Elsie, "I'm pleased to explain what I shall
do: I shall drink lemonade and sit with the fat woman if there's room
for both of us on the same plank!"
The friends were silent with their faces turned in the same
direction across the country—their land, the land of generations of
their people. This breaking up would be the end for them of the near
tie of soil and tradition and boyhood friendship and the friendship of
manhood.
"Well," said the doctor unsteadily, "this is what you have been
working for."
"Read that," he said a little sadly, and sadness was rare with him:
it was an advertisement for the town paper announcing for sale his
house and farm.
"So you have left your mistress by herself," the master called out
to them as they passed. They replied with their bashful hilarity that
she herself had sent them away, that she was glad to be well rid of
them. As the wagon regained the middle of the road and
disappeared, Professor Ousley looked at the doctor with a meaning
that may have been deeper than his smile:—
"She sent us away, too—me and the children. She wanted the day
to herself. Of course this change, the going away, the wrenching
loose from memories of life in the house there since our marriage—
of course, all that no other one of us can feel as she feels it. My
work marches away, I follow my work, she follows me, the children
follow her. Duty heads the procession. It pulls us all up by the roots
and drags us in the train of service: we are all servants, work is lord.
I understood her to-day—I was glad to bring the children and to be
absent from her myself: these hours of looking backward and of
looking forward are sacred to her—it is her woman's right to be
alone." He drew the doctor into these confidences as one not
outside intimate sacred things. The doctor made no reply.
He drove in.
Slowly the doctor's buggy began to enclose the house within this
circle, this coil, this arm creeping around and enclosing a form.
In spots along the drive the shrubbery was dense, and forest
trees overhung. He had scarcely entered it when a bird flitted across
his path: softest of all creatures that move on wings, with its long
gliding flight, a silken voluptuous grace of movement—the rain-crow.
It flew before him a short distance and alighted on a low
overhanging bough—its breast turned, as waiting for him. Its wings
during that flight resembled the floating draperies of a woman
fleeing with outstretched arms; and as it now sat quiet and inviting,
its throat looked like a soft throat—bared.
She had bespoken a day for solitude. And now she sat there,
deep in the reverie of the years.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com