0% found this document useful (0 votes)
12 views85 pages

Data Abstraction Problem Solving With Java Walls and Mirrors 3rd Ed Prichard PDF Download

The document provides information about the book 'Data Abstraction and Problem Solving with Java: Walls and Mirrors, 3rd Edition' by Janet Prichard and Frank Carrano, including links to download various editions and related materials. It outlines the contents of the book, which covers problem-solving techniques, abstract data types, and Java programming fundamentals. Additionally, it includes a detailed table of contents highlighting chapters on recursion, data structures, and algorithm efficiency.

Uploaded by

bobancomisv0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views85 pages

Data Abstraction Problem Solving With Java Walls and Mirrors 3rd Ed Prichard PDF Download

The document provides information about the book 'Data Abstraction and Problem Solving with Java: Walls and Mirrors, 3rd Edition' by Janet Prichard and Frank Carrano, including links to download various editions and related materials. It outlines the contents of the book, which covers problem-solving techniques, abstract data types, and Java programming fundamentals. Additionally, it includes a detailed table of contents highlighting chapters on recursion, data structures, and algorithm efficiency.

Uploaded by

bobancomisv0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Data Abstraction Problem Solving With Java Walls

And Mirrors 3rd Ed Prichard download

https://ebookbell.com/product/data-abstraction-problem-solving-
with-java-walls-and-mirrors-3rd-ed-prichard-21347466

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

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

Instructors Manual Data Abstraction And Problem Solving With Java


Walls And Mirrors 3rd Edition Janet Prichard

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

Data Abstraction Problem Solving With C Walls Mirrors 5th Edition


Frank M Carrano

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

Data Abstraction Problem Solving With C International Edition 6th


Edition Frank M Carrano

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

International Edition contributions by


Indrajit Banerjee
Bengal Engineering and Science University
Editorial Director: Marcia Horton Acquisitions Editor, International Edition:
Editor-in-Chief: Michael Hirsch Arunabha Deb
Editorial Assistant: Stephanie Sellinger Publishing Assistant, International Edition:
Marketing Manager: Yezan Alayan Shokhi Shah
Marketing Coordinator: Kathryn Ferranti Senior Operations Supervisor: Alan Fischer
Vice President, Production: Vince O’Brien Operations Specialist: Lisa McDowell
Managing Editor: Jeff Holcomb Text Designer: Sandra Rigney
Senior Production Project Manager: Marilyn Lloyd Cover Designer: Jodi Notowitz
Publisher, International Edition: Angshuman Cover Image: Getty Images/Steve Wall
Chakraborty Full-Service Vendor: GEX Publishing Services
Printer/Binder: Courier Stoughton

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.

Copyright © 2011 Pearson Education Limited, Edinburgh Gate, Harlow.

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.

British Library Cataloguing-in-Publication Data


A catalogue record for this book is available from the British Library

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

ISBN 10: 0-273-75120-4


ISBN 13: 978-0-273-75120-5
Brief Contents

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

1.5 Useful Java Classes 56


The Object Class 56
The Array Class 58
String Classes 59
1.6 Java Exceptions 64
Catching Exceptions 64
Throwing Exceptions 71
1.7 Text Input and Output 73
Input 73
Output 75
The Console Class 78
1.8 File Input and Output 80
Text Files 82
Object Serialization 90
Summary 93 Cautions 96 Self-Test Exercises 96
Exercises 97 Programming Problems 102
2 Principles of Programming and
Software Engineering 105
2.1 Problem Solving and Software Engineering 106
What Is Problem Solving? 106
The Life Cycle of Software 107
What Is a Good Solution? 117
2.2 Achieving an Object-Oriented Design 119
Abstraction and Information Hiding 120
Object-Oriented Design 122
Functional Decomposition 124
General Design Guidelines 125
Modeling Object-Oriented Designs Using UML 126
Advantages of an Object-Oriented Approach 130
2.3 A Summary of Key Issues in Programming 131
Modularity 131
Modifiability 133
Ease of Use 135
Fail-Safe Programming 136
Style 142
Debugging 146
Summary 149 Cautions 150 Self-Test Exercises 150
Exercises 151 Programming Problems 156
3 Recursion: The Mirrors 161
3.1 Recursive Solutions 162
A Recursive Valued Method: The Factorial of n 165
A Recursive void Method: Writing a String Backward 172
Contents 9

3.2 Counting Things 183


Multiplying Rabbits (The Fibonacci Sequence) 183
Organizing a Parade 185
Mr. Spock’s Dilemma (Choosing k out of n Things) 188
3.3 Searching an Array 190
Finding the Largest Item in an Array 191
Binary Search 192
Finding the k th Smallest Item in an Array 196
3.4 Organizing Data 200
The Towers of Hanoi 200
3.5 Recursion and Efficiency 204
Summary 211 Cautions 211 Self-Test Exercises 212
Exercises 213 Programming Problems 219
4 Data Abstraction: The Walls 221
4.1 Abstract Data Types 222
4.2 Specifying ADTs 227
The ADT List 228
The ADT Sorted List 233
Designing an ADT 235
Axioms (Optional) 239
4.3 Implementing ADTs 242
Java Classes Revisited 243
Java Interfaces 245
Java Packages 248
An Array-Based Implementation of the ADT List 250
Summary 257 Cautions 257 Self-Test Exercises 258
Exercises 259 Programming Problems 262
5 Linked Lists 265
5.1 Preliminaries 266
Object References 266
Resizeable Arrays 272
Reference-Based Linked Lists 273
5.2 Programming with Linked Lists 277
Displaying the Contents of a Linked List 277
Deleting a Specified Node from a Linked List 279
Inserting a Node into a Specified Position of a Linked List 282
A Reference-Based Implementation of the ADT List 288
Comparing Array-Based and Reference-Based Implementations 292
Passing a Linked List to a Method 295
Processing Linked Lists Recursively 295
10 Contents

5.3 Variations of the Linked List 301


Tail References 301
Circular Linked Lists 302
Dummy Head Nodes 304
Doubly Linked Lists 304
5.4 Application: Maintaining an Inventory 308
5.5 The Java Collections Framework 314
Generics 315
Iterators 316
The Java Collection’s Framework List Interface 319
Summary 322 Cautions 324 Self-Test Exercises 325
Exercises 327 Programming Problems 331

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

7.5 Application: A Search Problem 402


A Nonrecursive Solution That Uses a Stack 404
A Recursive Solution 412
7.6 The Relationship Between Stacks and Recursion 415
Summary 417 Cautions 417 Self-Test Exercises 418
Exercises 419 Programming Problems 424
8 Queues 433
8.1 The Abstract Data Type Queue 434
8.2 Simple Applications of the ADT Queue 436
Reading a String of Characters 436
Recognizing Palindromes 437
8.3 Implementations of the ADT Queue 438
A Reference-Based Implementation 440
An Array-Based Implementation 443
An Implementation That Uses the ADT List 449
The JCF Interfaces Queue and Deque 450
Comparing Implementations 456
8.4 A Summary of Position-Oriented ADTs 457
8.5 Application: Simulation 458
Summary 468 Cautions 469 Self-Test Exercises 469
Exercises 470 Programming Problems 474
9 Advanced Java Topics 479
9.1 Inheritance Revisited 480
Java Access Modifiers 486
Is-a and Has-a Relationships 488
9.2 Dynamic Binding and Abstract Classes 490
Abstract Classes 493
Java Interfaces Revisited 498
9.3 Java Generics 499
Generic Classes 499
Generic Wildcards 501
Generic Classes and Inheritance 502
Generic Implementation of the Class List 505
Generic Methods 507
9.4 The ADTs List and Sorted List Revisited 508
Implementations of the ADT Sorted List That Use the ADT List 509
9.5 Iterators 513
Summary 517 Cautions 518 Self-Test Exercises 518
Exercises 519 Programming Problems 524
12 Contents

10 Algorithm Efficiency and Sorting 529


10.1 Measuring the Efficiency of Algorithms 530
The Execution Time of Algorithms 531
Algorithm Growth Rates 533
Order-of-Magnitude Analysis and Big O Notation 533
Keeping Your Perspective 539
The Efficiency of Searching Algorithms 541
10.2 Sorting Algorithms and Their Efficiency 542
Selection Sort 543
Bubble Sort 547
Insertion Sort 549
Mergesort 551
Quicksort 557
Radix Sort 569
A Comparison of Sorting Algorithms 571
The Java Collections Framework Sort Algorithm 572
Summary 576 Cautions 577 Self-Test Exercises 577
Exercises 578 Programming Problems 582
11 Trees 585
11.1 Terminology 586
11.2 The ADT Binary Tree 594
Basic Operations of the ADT Binary Tree 594
General Operations of the ADT Binary Tree 595
Traversals of a Binary Tree 598
Possible Representations of a Binary Tree 601
A Reference-Based Implementation of the ADT Binary Tree 605
Tree Traversals Using an Iterator 610
11.3 The ADT Binary Search Tree 618
Algorithms for the Operations of the ADT Binary Search Tree 624
A Reference-Based Implementation
of the ADT Binary Search Tree 639
The Efficiency of Binary Search Tree Operations 643
Treesort 648
Saving a Binary Search Tree in a File 649
The JCF Binary Search Algorithm 652
11.4 General Trees 653
Summary 655 Cautions 656 Self-Test Exercises 656
Exercises 658 Programming Problems 664
12 Tables and Priority Queues 667
12.1 The ADT Table 668
Selecting an Implementation 675
A Sorted Array-Based Implementation of the ADT Table 682
A Binary Search Tree Implementation of the ADT Table 685
Contents 13

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

Shortest Paths 831


Circuits 835
Some Difficult Problems 838
Summary 839 Cautions 840 Self-Test Exercises 840
Exercises 841 Programming Problems 844
15 External Methods 847
15.1 A Look at External Storage 848
15.2 Sorting Data in an External File 851
15.3 External Tables 859
Indexing an External File 861
External Hashing 865
B-Trees 869
Traversals 879
Multiple Indexing 881
Summary 882 Cautions 883 Self-Test Exercises 883
Exercises 883 Programming Problems 886

A A Comparison of Java to C++ 887

B Unicode Character Codes (ASCII Subset) 891

C Java Resources 892


Java Web Sites 892
Using Java SE 6 892
Integrated Development Environments (IDEs) 893
D Mathematical Induction 894
Example 1 894
Example 2 895
Example 3 896
Example 4 897
Example 5 897
Self-Test Exercises 898 Exercises 898
Glossary 901
Self-Test Answers 921
Index 945
Preface

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.

New in this edition


Uses Java 6: This edition has been thoroughly revised to be compatible with
the latest release of Java, known as Java 6. All code has been completely revised
to be Java 6 compliant. Generics are also an important part of Java 6, and this
material is discussed in depth in Chapter 9, and then used throughout the
remainder of the collections in the text.

Enhanced Early Review of Java: We have increased the amount of coverage of


the Java language in the first chapter of the book to help students make the transi-
tion from their introduction to Java course to this course. Chapter 1 provides a
15
16 Preface

concise review of important Java material, including brief discussions on


constructors, object equality, inheritance, and the Array class. A discus-
sion of the Console class from Java 6 was also added to Chapter 1.
Chapter 9 focuses on advanced Java techniques, and includes an enhanced
discussion of how to create an iterator class.

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.

Other enhancements: Additional changes aimed at improving the overall


usability of the text include new exercises and a new cleaner design that
enhances the book’s readability.

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.

Part 1: Problem-Solving Techniques. The first two chapters in Part 1


resemble an extension of an introductory course in that their emphasis is on
major issues in programming and software engineering. Chapter 3 introduces
recursion for those students who have had little exposure to this important
topic. The ability to think recursively is one of the most useful skills that a
18 Preface

Chapter 2
Principles Chapter 1
Java review

Chapter 4
Data abstraction
Chapter 3
Recursion
Chapter 5
Linked lists
Chapter 6
More recursion

Chapter 7 Chapter 8 Chapter 9 Chapter 10


Stacks Queues Advanced Java Algorithm efficienc y, sorting

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

Dependency by one section of chapter


Dependency that you can ignore
Knowledge of Java helpful to begin these chapters
Preface 19

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

application of stacks. Other applications include, for example, the Eight


Queens problem as an example of backtracking, event-driven simulation as an
application of queues, and graph searching and traversals as other important
applications of stacks and queues.

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

The following instructor supplements are only available to qualified


instructors. Please visit Addison-Wesley’s Instructor Resource Center
(www.pearsonhighered.com/irc) or contact your local Addison-Wesley
Sales Representative to access them.
 Instructor’s Guide with Solutions: This manual contains teaching hints,
sample syllabi, and solutions to all the end-of-chapter exercises in the
book.
 Test Bank: A collection of multiple choice, true/false, and short-answer
questions
 PowerPoint Lectures: Lecture notes with figures from the book

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:

Computer Science Editorial Office


Addison-Wesley
501 Boylston Street, Suite 900
Boston, MA 02116

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

Timothy Rolfe—Eastern Washington University


Hongjun Song—University of Memphis
For their peer reviews of the international edition, we would like to thank:
Arup Kumar Bhattacharjee—RCC Institute of Information Technology
Soumen Mukherjee—RCC Institute of Information Technology
We especially thank the people who produced this book. Our editors at
Addison-Wesley, Michael Hirsch and Stephanie Sellinger, provided invaluable
guidance and assistance. Also, Marilyn Lloyd, Linda Knowles, Yez Alayan and
Kathryn Ferranti contributed their expertise and care during the final produc-
tion and in the marketing of the book.
Many other wonderful people have contributed in various ways. They are
Doug McCreadie, Michael Hayden, Sarah Hayden, Andrew Hayden, Albert
Prichard, Frances Prichard, Sarah Mason, Karen Mellor, Maybeth Conway, Ted
Emmott, Lorraine Berube, Marge White, James Kowalski, Ed Lamagna, Gerard
Baudet, Joan Peckham, Victor Fay-Wolfe, Bala Ravikumar, Karl Abrahamson,
Ronnie Smith, James Wirth, Randy Hale, John Cardin, Gail Armstrong, Tom
Manning, Jim Abreu, Bill Harding, Hal Records, Laurie MacDonald, Ken
Fougere, Ken Sousa, Chen Zhang, Suhong Li, Richard Glass, and Aby
Chaudhury. In special memory of Wallace Wood.
Numerous other people provided input for the previous editions of Walls and
Mirrors at various stages of its development. All of their comments were useful and
greatly appreciated. In alphabetical order, they are: Stephen Alberg, Vicki Allan,
Jihad Almahayni, James Ames, Andrew Azzinaro, Tony Baiching, Don Bailey,
Wolfgang W. Bein, Sto Bell, David Berard, John Black, Richard Botting, Wolfin
Brumley, Philip Carrigan, Stephen Clamage, Michael Clancy, David Clayton,
Michael Cleron, Chris Constantino, Shaun Cooper, Charles Denault, Vincent J.
DiPippo, Suzanne Dorney, Colleen Dunn, Carl Eckberg, Karla Steinbrugge Fant,
Jean Foltz, Marguerite Hafen, George Hamer, Judy Hankins, Lisa Hellerstein, Mary
Lou Hines, Jack Hodges, Stephanie Horoschak, John Hubbard, Kris Jensen,
Thomas Judson, Laura Kenney, Roger King, Ladislav Kohout, Jim LaBonte, Jean
Lake, Janusz Laski, Cathie LeBlanc, Urban LeJeune, John M. Linebarger, Ken
Lord, Paul Luker, Manisha Mande, Pierre-Arnoul de Marneffe, John Marsaglia, Jane
Wallace Mayo, Mark McCormick, Dan McCracken, Vivian McDougal, Shirley
McGuire, Sue Medeiros, Jim Miller, Guy Mills, Cleve Moler, Paul Nagin, Rayno
Niemi, Paul Nagin, John O’Donnell, Andrew Oldroyd, Larry Olsen, Raymond L.
Paden, Roy Pargas, Brenda C. Parker, Keith Pierce, Lucasz Pruski, George B. Purdy,
David Radford, Steve Ratering, Stuart Regis, J. D. Robertson, John Rowe, Michael
E. Rupp, Sharon Salveter, Charles Saxon, Chandra Sekharan, Linda Shapiro, Yujian
Sheng, Mary Shields, Carl Spicola, Richard Snodgrass, Neil Snyder, Chris Spannabel,
Paul Spirakis, Clinton Staley, Matt Stallman, Mark Stehlick, Harriet Taylor, David
Teague, David Tetreault, John Turner, Susan Wallace, James E. Warren, Jerry Weltman,
Nancy Wiegand, Howard Williams, Brad Wilson, Salih Yurttas, and Alan Zaring.
Thank you all.
F. M. C.
J. J. P.
This page intentionally left blank
PART O NE

Problem-Solving
Techniques

T he primary concern of the six chapters in Part One of this book is to


develop a repertoire of problem-solving techniques that form the basis
of the rest of the book. Chapter 1 begins by providing a brief overview of
Java fundamentals. Chapter 2 describes the characteristics of a good solu-
tion and the ways to achieve one. These techniques emphasize abstraction,
modularity, and information hiding. The remainder of Part One discusses
data abstraction for solution design, more Java for use in implementations,
and recursion as a problem-solving strategy.
This page intentionally left blank
CHAPTER 1

Review of Java
Fundamentals

T his book assumes that you already know how to write


programs in a modern programming language. If that
language is Java, you can probably skip this chapter, return-
1.1 Language Basics
Comments
Identifiers and Keywords
Variables
ing to it for reference as necessary. If instead you know a Primitive Data Types
language such as C++, this chapter will introduce you to References
Java. Literal Constants
It isn’t possible to cover all of Java in these pages. Named Constants
Instead this chapter focuses on the parts of the language Assignments and Expressions
Arrays
used in this book. First we discuss basic language con-
structs such as variables, data types, expressions, opera- 1.2 Selection Statements
tors, arrays, decision constructs, and looping constructs. The if Statement
The switch Statement
Then we look at the basics of program structure, including
packages, classes, and methods, with a brief introduction to 1.3 Iteration Statements
inheritance. We continue with useful Java classes, excep- The while Statement
tions, text input and output, and files. The for Statement
The do Statement

1.4 Program Structure


Packages
Classes
Data Fields
Methods
How to Access Members of an Object
1.5 Useful Java Classes
The Object Class
String Classes
1.6 Java Exceptions
Catching Exceptions
Throwing Exceptions
1.7 Text Input and Output
Input
Output
1.8 File Input and Output
Text Files
Object Serialization
Summary 27
Cautions
28 Chapter 1 Review of Java Fundamentals

1.1 Language Basics


Let’s begin with the elements of the language that allow you to perform
simple actions within a program. The following sections provide a brief over-
view of the basic language constructs of Java.

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.

Identifiers and Keywords


A Java identifier is a sequence of letters, digits, underscores, and dollar signs
that must begin with either a letter or an underscore. Java distinguishes
Java is case between uppercase and lowercase letters, so be careful when typing identifiers.
sensitive You use identifiers to name various parts of the program. Certain identifi-
ers, however, are reserved by Java as keywords, and you should not use them
for other purposes. A list of all Java keywords appears inside the front cover of
this book. The keywords that occur within Java statements in this book are in
boldface.

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

Primitive Data Types


The primitive data types in Java are organized into four categories: boolean,
character, integer, and floating point. For example, the following two lines
declare variables of the primitive type double.

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:

int x = 9; You can represent


Integer intObject = new Integer(x); the value of a
System.out.println("The value stored in intObject = " primitive data type
by using a wrapper
+ intObject.intValue()); class

Category Data Type Wrapper Class


Boolean boolean Boolean
Character char Character
Integer byte Byte
short Short
int Integer
long Long
Floating point float Float
double Double

FIGURE 1-1

Primitive data types and corresponding wrapper classes


30 Chapter 1 Review of Java Fundamentals

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:

String name = new String("Sarah");

A special reference value of null is provided to indicate that a reference vari-


able has no object to reference.

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

System.out.println("Hello\n Let\'s get started!");

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

final float DEFAULT_RADIUS = 1.0;

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

Named constants declares DEFAULT_RADIUS as a named floating-point constant. Once a named


make a program constant such as DEFAULT_RADIUS is declared, you can use it, but you cannot
easier to read and assign it another value. By using named constants, you make your program
modify
both easier to read and easier to modify.

Assignments and Expressions


You form an expression by combining variables, constants, operators, and
parentheses. The assignment statement

An assignment radius = initialRadius;


statement assigns
the value of an
assigns to a previously declared variable radius the value of the expression on the
expression to a
variable right-hand side of the assignment operator =, assuming that initialRadius has
a value. The assignment statement

double radiusCubed = radius * radius * radius;

also declares radiusCubed’s data type, and assigns it a value.

Arithmetic expressions. You can combine variables and constants with


arithmetic operators and parentheses to form arithmetic expressions. The
arithmetic operators are

* Multiply + Binary add or unary plus


/ Divide - Binary subtract or unary minus
% Remainder after division

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 -)

-5 / a means (-5) / a ( precedence of unary operator -)


a / -5 means a / (-5) ( precedence of unary operator -)
Arithmetic operators and most other operators are left-associative. That
is, operators of the same precedence execute from left to right within an
expression. Thus,

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):

int → long → float → double


34 Chapter 1 Review of Java Fundamentals

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.

Explicit type conversions for primitive numeric types. Numeric conversions


from one type to another are possible by means of a cast. The cast operator is a
unary operator formed by enclosing the desired data type within parentheses.
Thus, the sequence

double volume = 14.9;


You convert from System.out.print((int)volume);
one numeric type
to another by using
displays 14.
a cast

Multiple assignment. If you omit the semicolon from an assignment state-


ment, you get an assignment expression. You can embed assignment expres-
sions within assignment expressions, as in a = 5 + (b = 4).

This expression first assigns 4 to b and then 9 to a. This notation contributes to


the terseness of Java and is sometimes convenient, but it can be confusing. The
assignment operator is right-associative. Thus, a = b = c means a = (b = c).

Other assignment operators. In addition to the assignment operator =, Java


provides several two-character assignment operators that perform another
operation before assignment. For example,
a += b means a = a + b

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:

final int DAYS_PER_WEEK = 7;


double [] maxTemps = new double[DAYS_PER_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

maxTemps 82.0 71.5 61.8 75.0 88.3 0.0 0.0

maxTemps[4] Unused at present

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:

String[] stuNames = new String[10];

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:

stuName[0] = new String("Andrew");

Multidimensional arrays. You can use a one-dimensional array, which has


one index, for a simple collection of data. For example, you can organize 52
temperatures linearly, one after another. A one-dimensional array of these tem-
peratures can represent this organization.
An array can have You can also declare multidimensional arrays. You use more than one
more than one index to designate an element in a multidimensional array. Suppose that you
dimension wanted to represent the minimum temperature for each day during 52 weeks.
The following statements declare a two-dimensional array, minTemps:

final int DAYS_PER_WEEK = 7;


final int WEEKS_PER_YEAR = 52;

double[][] minTemps = new


double[DAYS_PER_WEEK][WEEKS_PER_YEAR];

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:

// minTemps is a two-dimensional array of daily minimum An example of using


// temperatures for 52 weeks, where each column of the a two-dimensional
// array contains temperatures for one week. array

// initially, assume the lowest temperature is


// first in the array
double lowestTemp = minTemps[0][0];
int dayOfWeek = 0;
int weekOfYear = 0;
38 Chapter 1 Review of Java Fundamentals

// search array for lowest temperature


for (int weekIndex = 0; weekIndex < WEEKS_PER_YEAR;
++weekIndex) {
for (int dayIndex = 0; dayIndex < DAYS_PER_WEEK;
++dayIndex) {
if (lowestTemp > minTemps[dayIndex][weekIndex]) {
lowestTemp = minTemps[dayIndex][weekIndex];
dayOfWeek = dayIndex;
weekOfYear = weekIndex;
} // end if
} // end for
} // end for
// Assertion: lowestTemp is the smallest value in
// minTemps and occurs on the day and week given by
// dayOfWeek and weekOfYear; that is, lowestTemp ==
// minTemps[dayOfWeek][weekOfYear].

It is entirely possible to declare minTemps as a one-dimensional array of


364 (7 * 52) elements, in which case you might use minTemps[81] instead of
minTemps[4][11] to access the minimum temperature on the 4th day of the
11th week. However, doing so will make your program harder to understand!
Although you can declare arrays with more than two dimensions, it is unusual
to have an array with more than three dimensions. The techniques for working
with such arrays, however, are analogous to those for two-dimensional arrays.
You can initialize the elements of a two-dimensional array just as you
initialize a one-dimensional array. You list the initial values row by row. For
example, the statement

int[][] x = {{1,2,3},{4,5,6}};

initializes a 2-by-3 array x so that it appears as


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.

1.2 Selection Statements


Selection statements allow you to choose among several courses of action
according to the value of an expression. In this category of statements, Java
provides the if statement and the switch statement.
Selection Statements 39

The if Statement
You can write an if statement in one of two ways:

if (expression) An if statement has


statement1 two basic forms

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

System.out.println(larger + " is the larger value.");


40 Chapter 1 Review of Java Fundamentals

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:

You can nest if if ((a >= b) && (a >= c)) {


statements largest = a;
}
else if (b >= c) { // a is not largest at this point
largest = b;
}
else {
largest = c;
} // end if

The switch Statement


When you must choose among more than two courses of action, the if state-
A switch state- ment can become unwieldy. If your choice is to be made according to the
ment provides value of an integral expression, you can use a switch statement.
a choice of several For example, the following statement determines the number of days in a
actions according to
month. The int variable month designates the month as an integer from 1 to 12.
the value of an inte-
gral expression
switch (month) {
// 30 days hath Sept., Apr., June, and Nov.
Without a break case 9: case 4: case 6: case 11:
statement, execu- daysInMonth = 30;
tion of a case will break;
continue into the // all the rest have 31
next case case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;

// 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

Parentheses must enclose the integral switch expression—month, in this


example. The case labels have the form

case expression:

where expression is a constant integral expression. After the switch expression


is evaluated, execution continues at the case label whose expression has the
same value as the switch expression. Subsequent statements execute until
either a break or a return is encountered or the switch statement ends.
It bears repeating that unless you terminate a case with either a break or a
return, execution of the switch statement continues. Although this action can be
useful, omitting the break statements in the previous example would be incorrect.
If no case label matches the current value of the switch expression, the
statements that follow the default label, if one exists, are executed. If no
default exists, the switch statement exits.

1.3 Iteration Statements


Java has three statements—the while, for, and do statements—that provide
for repetition by iteration—that is, loops. Each statement controls the number
of times that another Java statement—the body—is executed. The body can be
a single statement, though this text will always use a compound statement.

The while Statement


The general form of the while statement is

while (expression) A while statement


statement executes as long
as the expression
As long as the value of expression is true, statement is executed. Because expression is true
is evaluated before statement is executed, it is possible that statement will not
execute at all. Note that the parentheses around expression are required.
Suppose that you wanted to compute the sum of a list of integers stored in
an array called myArray. The following while loop accomplishes this task:

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.

The for Statement


The for statement provides for counted loops and has the general form

A for statement for (initialize; test; update)


lists the initializa- statement
tion, testing, and
updating steps in
one location
where initialize, test, and update are expressions. Typically, initialize is an
assignment expression that initializes a counter to control the loop. This ini-
tialization occurs only once. Then, if test, which is usually a logical expression,
is true, statement executes. The expression update executes next, usually incre-
menting or decrementing the counter. This sequence of events repeats, begin-
ning with the evaluation of test, until the value of test is false. As with the
previous constructs, statement is usually a compound statement.
For example, the following for statement sums the integers from 1 to n:

int sum = 0;
for (int counter = 1; counter <= n; ++counter) {
sum += counter;
} // end for

// this statement is always executed


int x = 0;

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;

In general, the logic of a for statement is equivalent to

A for statement is initialize;


equivalent to a while (test) {
while statement statement;
update;
} // end while
Iteration Statements 43

with the understanding that if statement contains a continue, update will


execute before test is evaluated again.
The following two examples demonstrate the flexibility of the for statement:

for (byte ch = 'z'; ch >= 'a'; --ch) {


// ch ranges from 'z' to 'a'
statements to process ch
} // end for

for (double x = 1.5; x < 10; x += 0.25) {


// x ranges from 1.5 to 9.75 at steps of 0.25
statements to process x
} // end for

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:

// floating-point power equals floating-point x


// raised to int n; assumes integer expon
for (power = 1.0, expon = 1; expon <= n; ++expon){
power *= x;
} // end for

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

This loop is equivalent to the following for statement:

for (int i = 0, sum = 0; i < x.length; sum += x[i++]) {


}

In fact, this for statement has an empty body!


44 Chapter 1 Review of Java Fundamentals

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

This for statement offers no advantage over the equivalent while


statement:

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:

for (ArrayElementType variableName : arrayName)


statement

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:

String[] nameList = { "Janet", "Frank", "Mike", "Doug"};


for (string name: nameList) { // for each name in nameList
System.out.println(name);
} // end for
Program Structure 45

is equivalent to the following:

String[] nameList = { "Janet", "Frank", "Mike", "Doug"};


for (int index=0; index < nameList.length; index++) {
System.out.println(nameList[index]);
} // end for

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);

Here, statement executes until the value of expression is false.


For example, suppose that you execute a sequence of statements and then
ask the user whether to execute them again. The do statement is appropriate,
because you execute the statements before you decide whether to repeat them:

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') );

1.4 Program Structure


Let’s begin our discussion of program structure with the simple Java applica-
tion in Figure 1-5 that computes the volume of a sphere. It consists of two
classes, SimpleSphere and TestClass. Each of these classes is contained in a
separate file that has the same name as the class, with .java appended to the
end. A typical Java program consists of several classes, some of which you write
and some of which you use from the Java Application Programming Interface
(API). A Java application has one class that contains a method main, the start- Each Java applica-
ing point for program execution. Running the program in Figure 1-5 produces tion must contain at
the following output: least one class that
has a method main
The volume of a sphere of radius 19.1 inches is 29186.95

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

A simple Java application

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 package-name.class-name; The import state-


ment provides
access to classes
For example, line 2 in Figure 1-5 imports the class Math from the package within a package
java.lang. The following line also could have been used:

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()

creates an instance of the type SimpleSphere.


48 Chapter 1 Review of Java Fundamentals

Component Syntax Description

Subclassing abstract Class must be extended to be useful.


modifier
(use only one) final Class cannot be extended.

Access public Class is available outside of package.


modifiers
no access modifier Class is available only within package.

Keyword class class-name Class should be contained in a file called


class class-name.java.

extends extends Indicates that this class is a subclass of the class


clause superclass-name superclass-name in the extends clause.

implements implements Indicates the interfaces that this class implements.


clause interface-list The interface-list is a comma-separated list of
interface names.

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

Type of modifier Keyword Description

Access modifier public Data field is available everywhere (when the class is
(use only one) also declared public).

private Data field is available only within the class.

protected Data field is available within the class, available in


subclasses, and available to classes within the same
package.

No access Data field is available within the class and within


modifier the package.

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.

final The value provided for the data field cannot be


modified (a constant).

transient The data field is not part of the persistent state of


the object.

volatile The value provided for the data field can be


accessed by multiple threads of control. Java
ensures that the freshest copy of the data field is
always used.

FIGURE 1-7

Modifiers used in data field declarations

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."

The medical schools of those days, as members of the profession


yet living can testify if they would, had their stories of student life
that make good stories when recited around the fireside with
September rain on the roof. The former graduate and non-
practitioner was not averse seemingly to reminiscence. Forthwith he
entered upon some chronicles and pursued them with that soft, level
voice of either betting with you or baptizing you—the voice of
gambling in this world or of gambling for the next.

As the recitals wound along their channels, the listener's


enthusiasm became stirred: by degrees it took on a kindling that
was like a wild leaping flame of joy.

"But there always has to be a leader," he said, as though


forecasting for himself a place of such splendid prominence. "There
has to be a leader, a head."

"I was the head."


The young hunter on the opposite side of the fireplace suddenly
threw up his arms and rolled out of his chair and lay on the floor as
though he had received a charge of buckshot in one ear. At last,
gathering himself up on the floor, he gazed at the tranquil amber
pipe and tranquil piper:—

"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.

"Another shock like that——!" and the searcher for a profession


climbed with difficulty into his chair again. For a while there was
satisfied silence, and now things took on a graver character:—

"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.

"To be a soldier and to be a farmer—if I could get those two


professions together," persisted the youth.
"In times of peace there is only one profession that furnishes the
active soldier: and that is the profession of medicine. It is the
physician and the surgeon that the military virtues rest on; and the
martial traits when there is no war. It is these men that bring those
virtues and those traits undiminished from one war to the next war.
There is no kind of manhood in the soldier, the fighting man, that is
not in the fighting physician and fighting surgeon—fighting against
disease. There is nothing that has to be changed in these two when
war breaks out or when peace comes: their constant service fits
them for either. In times of peace the only warlike type of man
actively engaged in human life is the doctor and surgeon. Did you
ever think of that?" said the older man, persuasively.

The silence in the room grew deeper.

"Tell me about the professions in the War: what did they do about
it; how did they act?"

"The professions divided: some going with North, some going


with South; fighting on each side, fighting one another. The ministry
dividing most bitterly and sending up their prayers on each side for
the destruction of the other—to the same God. All except one: the
profession of medicine remained indivisible. For that is the
profession which has but a single ideal, a single duty, a single work,
and but one patient—Man."

The silence had become too deep for words.

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.

"I am going to be a Kentucky country doctor. Good night!" He


strode heavily out of the room, and his stride on the stairway
sounded like an upward march toward future glory.
The man at the fire listened. Usually when the youth had reached
his room above and set his candle on his stand beside his bed, he
undressed there as with one double motion of shucking an ear of
corn: half to right and half to left; and then the ear stood forth
bared in its glistening whiteness and rounded out to perfect form
with clean vitality. But now for a long time he heard a walking back
and forth, a solemn tread: life's march had begun in earnest.

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.

After winning a race, he always poured out a libation; and he


went to his sideboard now and poured out a libation sixteen years
old.

And he did not pour it on the ground.

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.

A return home then to a neighborhood of kinships and friendships


and to the uphill work which could so easily become downhill sliding
—the practice of medicine among a people where during these
absences he had been remembered, if remembered at all, as the
wildest youth in the country. When it had been learned what
profession he had chosen, the prediction had been made that within
a year Downs would reduce the mortality of the neighborhood to
normal—one to every inhabitant!

But at the end of this first year of undertaking to convert ridicule


into acceptance of himself as a stable health officer and confidential
health guardian, he was able to say that he had made a good start:
neighbors have long memories about a budding physician's first
cases—when he fails. Young Dr. Birney had not failed, because none
of his cases had been important: when there was danger, it was
considered safe to avoid the doctor: the only way in which he could
have lost a patient would have been to murder one! Thus he had
entered auspiciously upon the long art and science of securing
patients. But he had secured no wife! And he greatly preferred one
impossible wife to all possible patients. That problem meantime had
been pressing him sorely.

The womanless house in which he had been reared and his


boyhood on a stock farm had rendered him rather shy of girls and
kept him much apart from the society of the neighborhood.
Nevertheless even in Europe before his return—with the certainty of
marriage before him—he had recalled two or three juvenile
perturbations, and he had resolved upon arrival to follow these clues
and ascertain what changes seven years had wrought in them.
There was no difficulty in following the clues a few weeks after
getting back to Kentucky: they led in each case to the door of a
growing young family: and out of these households he thereupon
began to receive calls for his services to sick children: all the
perturbations had become volcanoes, and were now on their way to
become extinct craters.

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.

Moreover, he was pleasantly conscious of a general commotion of


part of the population toward him with reference to life's romance.
The girls of that race and land were much too healthy and normally
imaginative not to feel the impact of the arrival of a young doctor—
who was going to ask one of them to marry him. As to those seven
years of his in New York and Europe, he could discover only one
mind in them: they deplored his absence not because they had
missed him, but because he had missed them: it was no gain to
have been in New York and Berlin and Vienna if you lost Kentucky!
He gradually acquired the feeling that if in addition to the misfortune
of having been absent for several years, the calamity had been his of
having been born abroad, it would not have been permitted him to
plough corn.

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.

They were everywhere! As he drove widely about the country, the


two most abundant characteristics seemed to be unequalled grass
and marriageable girls. He met them on turnpikes and lanes—in
leafy woods at picnics—at moonlight dances—on velvet lawns—amid
the roses of old gardens—and he began humorously to count those
who looked available. One passed him on the road one day, and,
lifting a corner of the buggy curtain, she peeped back at him: "She
will do!" he said. Another swept past him on horseback and looked
in the opposite direction. "She will do!" he said. He met two on a
shady street of a quiet town under their peach-blow parasols: "They
will do!" he said. He saw four on a lawn playing tennis, and watched
their vital abandon and tasted their cup: "They will do!" he said. He
swept his eyes over a ball-room one night: "They will all do!" he
said, and made an end of counting.

Into this world of romance and bride-seeking the doctor launched


himself formally under brilliant auspices of earth and sky and people
one beautiful afternoon of early summer: it was on the grounds of
one of the finest old country places at a lawn party with tennis
matches. It was his first appearance as a candidate for life's greater
game. A large gallery of onlookers, seated along a trellis of vines
and roses, measured him critically as he stepped out on the court:
he knew it and he challenged the criticism. In his white flannels; his
big bared head covered with curling black hair; his neck half bare in
its virile strength; his big grayish blue eyes flashing with glorious
health, full of good humor and of deeper warmth; his big half-bared
arms strong to hold in love or to lift in pain; the big stub nose of
tenacity; the big red mouth that laughing revealed the big thick
white teeth, good to tear and grind their way: his twenty-six years of
native Kentucky insolence capped with a consciousness of travel and
knowledge of his own authority and power—youthful white soldier of
the clean,—the neighborhood's evangelist of life and death,—he
looked like a good partner for the afternoon or for life. One girl,
seeing all this—and more—repeated to herself, she did not know
why, Blake's poem on the Tiger.

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!

"That little foot," he said, moved to admiration, "that little foot


makes the true footprint of the greater vanished people! She is of
the blood of male and female heroes: she knows how to do and she
knows how to suffer! Now if I fall in love with her—!" and there
surged through him the invitation to do so.

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.

On the other hand, there were two or three cases of wounded on


the other side; and if one could have been privileged to stand near,
it would have been possible to see Love's ambulances secretly and
mournfully moving here and there to the rear. If as much as this
could not be said for him, what right would he have had to be
practising there—or to be alive anywhere!
And now the winter of that first year had come: it brought an
immense stride—in Progress.

It was the twenty-fourth of December. Darkness was beginning to


fall on road and woods and fields; and he was driving rapidly home
because he was tired and ravenous and because he was thinking of
his supper—always that good Kentucky supper. But to-night he
would have to eat solitary because some days previous his uncle had
gone to New York—gone in his quiet way: announcing the fact one
morning and stopping there—his reasons were his own.

About a mile from home the doctor's horse, rushing on through


the gathering Christmas twilight, began to overtake a vehicle moving
at a stately pace as though its mission involved affairs too elaborate
for haste. As he approached from the rear he recognized that it was
Frederick Ousley's carriage, returning from his afternoon wedding
several miles across the country.

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.

Christmas Eve—Night of Nativity—Home—Youth—Love—Firelight


and Darkness—One another!

As the doctor watched, that vision sank into him as an arrow


which had been shot into the air years before and had now hit its
mark. He straightened himself abruptly and gave the rein to his
horse with a feeling that the shaft stuck in its wound. Then with a
vigorous shake of his head he said to himself:—

"Dr. Birney, there is a young man in this buggy who needs your
best attention: see that he gets it and gets it quickly."

He found his supper awaiting him: and some intelligence which


drove appetite away and drove him away, leaving the supper
uneaten: it was a letter from his uncle—one of those tranquil letters:

"They think they will have to perform an operation on me, but I


want your opinion first. I trust your judgment beyond that of any of
them, old and experienced as they are: and I should have sought
your judgment before coming away if I could have felt sure that it
would be needed: unless it were needed, I did not wish you to
know. You had better start without losing very much time. They
seem to regard the case as urgent and uncertain.

"If anything should happen before you are able to reach me,
these few words will be my last.

"You have long since entered, Downs, into possession of part of


what you will inherit from me: and that is your acquaintance with
the imperfections of my character and the frailties of my life. There
has been much in it that even a worse man might regret, but
nothing of which any better man could be ashamed. You have
always guarded this part of your inheritance as your sacred private
personal property. My request is that you will hereafter make as little
account of it as possible; I hope you will never be tempted to draw
upon it as a valuable fund; and as early as time permits, put the
memory of it away to gather its oblivion and its dust.

"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!

"If this is good-by—good-by."

It was several weeks before he returned, bringing with him all


that was earthly of one whose races were over and who himself had
just been entered for the unknown stake of the Great Futurity.

Now February had reappeared, and with it came another stage of


Progress. When he entered the breakfast room one morning—always
to a hearty breakfast—he went first to the windows and looked out
at the low dark clouds shrouding the sky and the rapidly whitening
earth: it was snowing heavily. As he turned within, the bleakness out
of doors brightened the fire and added its comfort to the breakfast
table. While he was pouring out his coffee, suddenly through one
window an object appeared; and looking out, he saw Frederick
Ousley on horseback at the foot of the pavement: he was but half
seen, laughing and beckoning amid the thickly falling flakes.

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.

Two products of that land. With much in sympathy, with no


outward resemblance: one of little mingled Anglo-Saxon blood: the
other of Scotch-Irish Anglo-Saxon strains which have created so
much history wherever they have made their mortal fight. The
young Kentucky Anglo-Saxon on his horse, blond-haired, blue-eyed,
with heavy body and heavy limbs, a superb animal to begin with,
wheresoever and in whatsoever the animal might end: the snow on
the edges of his yellowish hair and close-clipped beard; around his
neck, just visible inside his upturned coat collar, a light blue scarf, a
woman's scarf, tied there as he had started by tender fingers that
had perhaps craved the mere touching of his flesh: the scarf, as it
were, of Lohengrin blue; for there was something so knightly about
him, he radiated such a passion of clean young manhood, that you
all but thought of him as a Kentucky Lohengrin—whom no Elsa had
questioned too closely, and for whom there would never be a barren
return to Montserrat.

Facing him, the young Kentucky Scotch-Irish Anglo-Saxon,


physical equal, physical opposite: dark and swarthy soldier of the
South: as he stood there giving you no notion that for him waited
the crimson-dyed cup of Life's tragic brew, topped at this moment
with the white dancing foam of youth and happiness.

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."

Then he added with affectionate seriousness: "I have told her


about you: how we have known each other all our lives, have played
together, hunted together, slept together, travelled together, studied
together. She knows all about you! I have prepared the way for you
to be her physician. There was a great difficulty there—that question
of her physician: you will know that, when you know her!"

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.

"I will come at once."

Young Ousley, with a sudden impulse, perhaps to conceal his own


sacred emotion, rode over to a window of the breakfast room and
peered in at the waiting table with its solitary chair at the head. He
raised his voice as though speaking to an imaginary person inside:

"How do you do, Mrs. Birney?" he said. "Could I speak to the


doctor a moment? I should like to have his private ear
professionally: could you pass one of his ears out?"

The doctor stooped and scraped together a snowball from the


edge of the porch, and with a soft toss hit him in the face:—

"Take that for speaking to Mrs. Birney through a window! And


Mrs. Birney is not my office boy. And I do the passing out of my own
ears—to any desired distance."

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."

It was the last playfulness of boyhood friendship, of a return to


old ways of jesting when jesting meant nothing. But the glance into
the breakfast room—those rallying words—the return of the snowball
into the face—were the ending of a past: each felt that this was
enough of it.

As young Ousley rode away, he wheeled his horse at the distance


of some yards and called back formally:—

"Mrs. Ousley would like to see you as soon as you can come,
doctor."

It was a professional command.

"I'll come immediately after breakfast."

"Thank you."

"Thank you!"

They had assumed another relation in life: on one side of a chasm


was a young husband with his bride; on the other, the family
physician.

As Dr. Birney poured out his coffee and buttered his biscuit, he
said to himself that now the bread of life was being buttered.

When he reached the Ousleys', the youthful husband met him on


the veranda and threw an arm around his shoulder affectionately
and led him in; and when some time later they reappeared, both
talked gravely and parted, bound by a new bond of dependence and
helpfulness between man and man.
For the next few days there developed in Dr. Birney a novel
consciousness that his interest in marriage had enormously
deepened, but that interest in his own marriage had received a
setback: the feeling was genuine, and it troubled him. The tentative
advances into social life that he had been making seemed to have
ended in blind paths; the growing ties snapped like threads upon
which some displaced weight has fallen.

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.

During the following weeks he was often at the Ousleys'—to


supper, as a guest in their carriage on visits and to parties: the three
were almost inseparable. One night at supper young Ousley again
brought up the subject of the doctor's marriage and twitted him for
hesitancy: unexpectedly the subject was thrust back into the
speaker's teeth: there was an awkward silence—very curious—
And now there befell the doctor one of those peculiar little
progressions or retrogressions which prove a man not to be utterly
forlorn. He had ceased to make social calls, and had begun to
decline invitations; and so into the air there was wafted that little
myth which went wandering over the country from house to house:
the familiar little myth that he had been rejected. This myth of the
rejected!—this little death-web wound about the unsuccessful suitor:
every eligible man is as much entitled to one as every caterpillar to
his cocoon.

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.

"There is only one way out of it for me," he muttered bitterly as


he went down the steps. "I must marry and fall in love with my own
wife and with the mother of my own children."

That afternoon he drove toward the stately homestead of the


summer lawns and tennis matches—but when he reached the front
gate, he drove past.

It was a few months after this, toward the end of a long


conversation with Mrs. Ousley, in which she now broached with
feminine tact and urgency the subject of his marriage, it was as he
told her good-by that there escaped from him the first intimation of
his love—unexpectedly as an electric spark flashing across a
vacuum.

When he was miles away he said to himself:

"This must stop—this must be stopped: if I cannot stop it, some


one else must help me to stop it."

That afternoon he began again his visits to the stately homestead


of the lawns and the tennis courts; and a month or two later he
drove by and said to Mrs. Ousley:—

"I am engaged to be married."

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.

One beautiful summer night of the year following there were


bridal fights gleaming far and wide over the grounds of this stately
country place and from all the windows of the house.

The doctor was married.

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.

A few miles up the pike he was surprised to meet a well-known


physician from the city: they knew each other socially and checked
their horses to exchange greetings.

Dr. Birney lost no time in saying:—

"If you are on the way to my house, I'll turn back."

"I'm going to the Ousleys'. Professor Ousley asked me yesterday


to come out and see Mrs. Ousley: he said it was her wish."

The two physicians quickly parted with embarrassment.

As Dr. Birney drove on he had received the wound which


sometimes leaves a physician with the feeling that he has tasted the
bitterness of his own death: he himself had been pushed aside—
discarded from the household that meant most to him as physician
and man.

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.

"It is their good-by to me," he said; "when my wife knows that


they have discharged me, as a woman understands another woman
in such a matter, she will know the reason; and she will see fully at
last what she began to see long since."

When he went to the Ousleys', Mrs. Ousley came forward to greet


him at the side of her husband, and she gave him both hands. And
she did what she had never done before—she tried with her little
hands to take his big ones—the hands that had saved her life; and
out of the intensity and solemnity of her gratitude she looked him in
the eyes until the lids fell over hers. It was like saying:—

It is not your fault, it is not my fault, it is not the fault of any of


us: it is life and the fault of life. As I let you go, dear friend, I cling
to you.

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 now more years—years—years! But what effect have years


upon the master passions? What are five years to a master Hatred?
What are ten years to Revenge? What are twenty to Malice? What is
half a century to Patience, or fourscore years to Loyalty, or fourscore
and ten to Friendship, or the last stretch of mortality to waiting
Love? The noble passions grow in nobility; the ignoble ones grow in
ignominy.

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.

Intervening years had developed the doctor in two phases of


growth: he looked no older, but he was heavier in trunk and limbs;
and he was weightier in repute, for he had established far and near
his fame as a physician. He had patients in remote county seats
now, and on this day he had been to one of those county seats to
visit a patient, and had found him mending. As he quitted the house
with this responsibility dropped, it further reminded him that within
the range of his practice he had not for the moment a single case of
critical illness or of any great suffering. Whereupon he experienced
the relief, the elastic rebound, known perhaps only to physicians
when for a term they may take up relations of entire health and
happiness with their fellow-beings: and when you cease to deal with
pain, you begin to deal with pleasure.

With a new buoyancy of foot and feeling he started down to


Cheapside, the gathering-place for farmers and merchants and
friendly town folk—most of all on Saturdays. As he strolled along,
the recollection wandered back to him of how in years gone by—
when he was just old enough to begin to shave—it was the
excitement of the week to shave and take his bath and don his best
and come to town to enjoy Saturday afternoon on Cheapside. The
spirit of boyhood flowed back to him: he bathed in a tide of warm
mysterious waters.

When he reached the public square, he began to shake hands


and rub shoulders; and to nod at more distant acquaintances; and
once under the awning of a store for agricultural implements he
paused squarely before a group of farmers sitting about on ploughs
and harrows. They were all friends, and at the sight of him they rose
in a group, seized him and marched him off with them to the hotel
to dinner whither they were just starting. They were hearty men; it
was a hearty meal; there was hearty talk, hearty laughter. Middle-
aged, red-blooded men of overflowing vitality, open-faced,
sunbrowned; eating meat like self-unconscious carnivora and
drinking water like cattle: premium animals in prime condition and
ready for action: on each should have been tied the blue ribbon of
agricultural fairs.

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.

The doctor's dinner companions were to join their wives and


children at the grounds, and very reluctantly he declined their urging
to go along: as they separated, there rose in him fresh temptation
about old Saturday afternoon liberties and pleasures—and there fell
upon him as a blight the desolation of his own home life.

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.

When he reached the outskirts of the town, he met vehicles


hurrying in from the neighborhood and from far beyond it.

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:—

"Where are you running off to?" he asked, pretending not to


remember that permission had been granted weeks before, as soon
as the bills had been pasted on turnpike fences.

"We're running off to the circus!"

"And what can you possibly be going to do at the circus? Children


go to a circus—who ever heard of such a thing! I should think you'd
have stayed at home and studied arithmetic or memorized the
capitals of all the States."

"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!"

"And what are you going to do?"

"I'm going to do everything, of course! That's my ticket: I don't


pay for all and see some! I'm going to do everything."

"Everything is a good deal," commented the doctor


introspectively. "Everything is a good deal; but do what you can
toward it—as you have paid the price."

For a while he mused how childhood wants all of whatever it


craves: its desire is as single as its eye. Only later in life we come to
know—or had better know—that we may have the whole of very
little: that a small part of anything is our wisest portion, and the
instant anything becomes entirely ours, it becomes lost to us or we
become lost to it: the bright worlds that last for ages revolve—they
do not collide.

He was still thinking of this when he met the carriage of Professor


Ousley; and the two middle-aged friends, who in their lives had
never passed each other on the road without stopping, stopped now.
Professor Ousley got out and came across to the doctor's buggy and
greeted him with fresh concerned cordiality.

"It has come at last," he announced, as though something long


talked of between them could be thus referred to; and he drew out a
letter which he handed in to be read; it was a call to a professorship
in a Northern university. As the doctor read it and reread it
(continuing to read because he did not know what to say)—as he
thus read, he began to look like a man grown ill.

"You have accepted, of course," he said barely.

"I have accepted."

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."

"This is what I have been working for," assented Professor Ousley.

These intermediate years had wrought their changes in him also;


within and without; he was grown heavy, and as an American
scholar he had weight. The doctor clung for safety to his one theme:

"You have outgrown your place here in Kentucky. A larger world
has heard of you and sends for you because it needs you. Well
done! But when I became a Kentucky country doctor, it was for life.
No greater world for me! My only future is to try to do better the
same work in the same place—always better and better if possible
till it is over. You climb your mountain range; I stay in my valley."

Professor Ousley drew out another envelope:

"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.

"It is the beginning of the end," he said. "It is our farewell to


Kentucky, to you, to our past, but not, I hope, to our future. Herbert
and Elizabeth will have to be looked out for in the future: Elizabeth
may refuse to leave the neighborhood, who knows?" He laughed
with fatherly fondness and gentleness.

The doctor laughed with him: that plighting of their children!

At this moment a spring wagon came hastening on: it was the


servants of the Ousley household.

"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 on now, not aware how he drove. A few more vehicles


passed, and then a mile or two farther out no more: they had
ceased to come: he was entering the silent open country.

A Kentucky landscape of August afternoon—Saturday afternoon!


The stillness! The dumb pathos of garnered fields—that spectacle of
the great earth dutiful to its trust and now discharged of obligation!
That acute pang of seeing with what loyalty the vows of the year
have been kept by soil and sun, and are ended and are now no
more! The first intimations also of changes soon to come—the chill
of early autumn nights when the moon rises on the white frost of
fences and stubble, and when outside windows glowing with kindled
hearths the last roses freeze. Of all seasons, of all the days with
which nature can torture us, none so wound without striking; none
awaken such pain, such longing: all desire offers itself to be
harvested.

There was no glare of sunlight this afternoon, nor any shape of


cloud, but a haze which took away shadows from fences and bushes
and wayside trees and weeds, and left the earth and things on it in a
radiance between light and shadow—between day and darkness. It
was a troubled brooding: and when the surfaces are quiet, then
begins the calling of the deeps to the deeps.

As the doctor advanced into this stillness of the land, there


reached his ear, as one last reverberation, that long lonely roar of
the great animal homesick and life-sick for jungle and jungle
freedom; for the right to be what nature had made it—rebellious
agony!
A day to herself! She had sent them all away, husband, and
children, and servants! The right to be alone with memories ... under
the still surface the invitation of the deeps....

Dr. Birney's buggy was nearing the front gate of Professor


Ousley's farm. When he reached it, he checked his horse and sat
awhile. Then he got out and looked up the pike and down the pike:
it might have been an instinct to hail any one passing—he looked
dazed—like a man not altogether under self-control. Not a soul was
in sight.

He drove in.

The main driveway approached the house almost straight; but a


few yards inside the gate there branched from it another which led
toward the sequestered portions of the grounds. It was private and
for pleasure: it formed a feature of the landscape gardening of
earlier times when country places were surrounded by parklike lawns
and forests and stone fences. It skirted the grounds at a distance
from the house, passed completely round it, and returned to the
main driveway at the point where it started. Thus it lay about the
house—a circle.

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.

Once the doctor's buggy passed a flower-bed the soil of which


showed signs of having been lately upturned: a woman's trowel lay
on the edge of the sod: some one had been working there; perhaps
some deep restlessness had ended the work. Here the atmosphere
was sweet with rose geranium and heliotrope: it was the remotest
part of the ground, screened from any distant view. And once the
buggy curtains struck against the spray of a rosebush and the petals
fell on the empty cushion beside the doctor and upon his knees. The
horse moved so slowly along this forest path of beauty and privacy
that no ear could have heard its approach as it passed round the
house and returned to the main drive. Here the doctor sat awhile.

Then he pulled the head of the horse toward the house.

He reached the top of the drive. At the end of a short pavement


stood the house. The front doors were closed—not locked. It stood
there in the security of its land and of its history, and of traditions
and ideals. Undefended except by these: with faith that nothing else
could so well defend.

On one side of the pavement was built an old-fashioned ornament


of Southern lawns—a vine-covered, rose-covered summer-house
within which could be seen rugs and chairs and a worktable: some
one had been at work; that same deep restlessness had perhaps
terminated pastime here. Near the other end of the house two glass
doors, framed like windows, opened upon a single stone step in the
grass; and within these doors hung a thin white drapery of summer
curtains; and under the festoon of these curtains there was visible
from the doctor's buggy half the still figure of a woman—reclining.

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.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like