100% found this document useful (4 votes)
76 views

Data Structures and The Java Collections Frameworks 3rd Edition William J. Collins All Chapter Instant Download

ebook

Uploaded by

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

Data Structures and The Java Collections Frameworks 3rd Edition William J. Collins All Chapter Instant Download

ebook

Uploaded by

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

Full download ebook at ebookname.

com

Data Structures and the Java Collections


Frameworks 3rd Edition William J. Collins

https://ebookname.com/product/data-structures-and-the-java-
collections-frameworks-3rd-edition-william-j-collins/

OR CLICK BUTTON

DOWLOAD NOW

Download more ebook from https://ebookname.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Object Oriented Data Structures Using Java Chip Weems

https://ebookname.com/product/object-oriented-data-structures-
using-java-chip-weems/

Data Structures and Abstractions with Java 4th Edition


Frank M. Carrano

https://ebookname.com/product/data-structures-and-abstractions-
with-java-4th-edition-frank-m-carrano/

Java Methods A Ab Object oriented Programming and Data


Structures Maria Litvin

https://ebookname.com/product/java-methods-a-ab-object-oriented-
programming-and-data-structures-maria-litvin/

Data Structures and Algorithms in Java 5th


International student edition M.T. Goodrich And R.
Tamassia

https://ebookname.com/product/data-structures-and-algorithms-in-
java-5th-international-student-edition-m-t-goodrich-and-r-
tamassia/
Data Structures with C Using STL 2nd Edition William H.
Ford

https://ebookname.com/product/data-structures-with-c-using-
stl-2nd-edition-william-h-ford/

Scripting in Java Languages Frameworks and Patterns 1st


Edition Dejan Bosanac

https://ebookname.com/product/scripting-in-java-languages-
frameworks-and-patterns-1st-edition-dejan-bosanac/

Java RMI 1st Edition William Grosso

https://ebookname.com/product/java-rmi-1st-edition-william-
grosso/

Purely functional data structures 1st Edition Okasaki

https://ebookname.com/product/purely-functional-data-
structures-1st-edition-okasaki/

Advanced Data Structures 1st Edition Peter Brass

https://ebookname.com/product/advanced-data-structures-1st-
edition-peter-brass/
This page intentionally left blank
Data Structures and the
Java Collections Framework
This page intentionally left blank
Data Structures and the
Java Collections Framework

Third Edition

William J. Collins
Lafayette College

JOHN WILEY & SONS, INC.


Vice President and Executive Publisher: Donald Fowley
Executive Editor: Beth Lang Golub
Editorial Assistants: Michael Berlin, Elizabeth Mills
Marketing Manager: Chris Ruel
Senior Production Manager: Janis Soo
Assistant Production Editor: Annabelle Ang-Bok
Designers: Seng Ping Ngieng
Cover Photo: © Jose Ignacio Soto/iStockphoto

This book was set in 10/12 Times Roman by Laserwords and printed and bound by Malloy Lithographers. The cover was printed by Malloy
Lithographers.

This book is printed on acid free paper.

Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping
people around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include
responsibility to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global
effort to address the environmental, social, economic, and ethical challenges we face in our business. Among the issues we are addressing
are carbon impact, paper specifications and procurement, ethical conduct within our business and among our vendors, and community and
charitable support. For more information, please visit our website: www.wiley.com/go/citizenship.

Copyright © 2011 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or
transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under
Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc. 222 Rosewood Drive, Danvers, MA 01923,
website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley &
Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201)748–6011, fax (201)748–6008, website http://www.wiley.com/go/permissions.

Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next
academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please
return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at www.wiley.com/go/
returnlabel. Outside of the United States, please contact your local representative.

Library of Congress Cataloging-in-Publication Data

Collins, William J. (William Joseph)


Data structures and the Java collections framework / William Collins. – 3rd ed.
p. cm.
Includes bibliographical references and index.
ISBN 978-0-470-48267-4 (paperback)
1. Java (Computer program language) 2. Data structures (Computer science) I. Title.
QA76.73.J38C657 2011
005.7 3–dc22
2010043311
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
To Jayden—my fountain of youth

—W.J.C.
This page intentionally left blank
BRIEF CONTENTS

Preface xvii

CHAPTER 0
Introduction to Java 1

CHAPTER 1
Object-Oriented Concepts 27

CHAPTER 2
Additional Features of Programming and Java 59

CHAPTER 3
Analysis of Algorithms 105

CHAPTER 4
The Java Collections Framework 133

CHAPTER 5
Recursion 155

CHAPTER 6
Array-Based Lists 233

CHAPTER 7
Linked Lists 267

CHAPTER 8
Stacks and Queues 329

vii
viii BRIEF CONTENTS

CHAPTER 9
Binary Trees 377

CHAPTER 10
Binary Search Trees 401

CHAPTER 11
Sorting 457

CHAPTER 12
Tree Maps and Tree Sets 501

CHAPTER 13
Priority Queues 551

CHAPTER 14
Hashing 599

CHAPTER 15
Graphs, Trees, and Networks 643

APPENDIX 1
Additional Features of the JAVA Collections Framework 701

APPENDIX 2
Mathematical Background 705

APPENDIX 3
Choosing a Data Structure 721

References 725

Index 727
CONTENTS

Preface xvii 1.3 Inheritance 37


1.3.1 The protected Visibility
Modifier 39
CHAPTER 0 1.3.2 Inheritance and Constructors 43
Introduction to Java 1 1.3.3 The Subclass Substitution Rule 43
1.3.4 Is-a versus Has-a 47
Chapter Objectives 1
1.4 Information Hiding 48
0.1 Java Fundamentals 1
1.5 Polymorphism 48
0.1.1 Primitive Types 2
1.6 The Unified Modeling Language 49
0.1.2 The char Type 2
Summary 52
0.2 Classes 3
0.2.1 The String Class 4 Crossword Puzzle 54
0.2.2 Using javadoc Notation for Method Concept Exercises 55
Specifications 5 Programming Exercises 56
0.2.3 Equality of References and Equality of Programming Project 1.1: A CalendarDate
Objects 7 Class 58
0.2.4 Local Variables 9
0.2.5 The Scanner Class 12
0.3 Arrays 17
CHAPTER 2
Additional Features of Programming
0.4 Arguments and Parameters 19 and Java 59
0.5 Output Formatting 22
Chapter Objectives 59
Crossword Puzzle 24
2.1 Static Variables, Constants and Methods 59
Programming Exercises 25
2.2 Method Testing 61
2.2.1 More Details on Unit Testing 64

CHAPTER 1 2.3 Exception Handling 68


2.3.1 Propagating Exceptions 71
Object-Oriented Concepts 27 2.3.2 Unit Testing and Propagated
Exceptions 74
Chapter Objectives 27
2.3.3 Checked Exceptions 77
1.1 Data Abstraction 27 2.3.4 The finally Block 81
1.2 Abstract Methods and Interfaces 28 2.4 File Output 81
1.2.1 Abstract Data Types and Data
2.5 System Testing 91
Structures 31
1.2.2 An Interface and a Class that 2.6 The Java Virtual Machine 92
Implements the Interface 31 2.6.1 Pre-Initialization of Fields 92
1.2.3 Using the FullTimeEmployee 2.6.2 Garbage Collection 92
Class 35 2.7 Packages 93

ix
x CONTENTS

2.8 Overriding the Object Class’s equals 4.2 Some Details of the Java Collections
Method 94 Framework 136
Summary 97 4.2.1 Abstract Classes 137
4.2.2 Parameterized Types 140
Crossword Puzzle 98
4.2.3 The Collection Interface 141
Concept Exercises 99 4.2.4 The List Interface 147
Programming Exercises 100 Summary 150
Programming Project 2.1: An Integrated Web Crossword Puzzle 151
Browser and Search Engine, Part 1 102
Concept Exercises 152
Programming Exercises 152
CHAPTER 3 Programming Project 4.1: Wear a Developer’s Hat
and a User’s Hat 153
Analysis of Algorithms 105
Chapter Objectives 105
3.1 Estimating the Efficiency of Methods 105
3.1.1 Big-O Notation 106
CHAPTER 5
3.1.2 Getting Big-O Estimates Quickly 110
Recursion 155
3.1.3 Big-Omega, Big-Theta and Plain Chapter Objectives 155
English 116 5.1 Introduction 155
3.1.4 Growth Rates 117
5.2 Factorials 156
3.1.5 Trade-Offs 119
5.2.1 Execution Frames 159
3.2 Run-Time Analysis 121
5.3 Decimal to Binary 162
3.2.1 Timing 121
3.2.2 Overview of the Random Class 122 5.4 Towers of Hanoi 167
5.4.1 Analysis of the move Method 177
Summary 126
5.5 Searching an Array 179
Crossword Puzzle 127
5.6 Backtracking 191
Concept Exercises 128
5.6.1 An A-maze-ing Application 195
Programming Exercises 130
5.7 Indirect Recursion 208
Programming Project 3.1: Let’s Make a
5.8 The Cost of Recursion 209
Deal! 131
Summary 210
Crossword Puzzle 211
CHAPTER 4 Concept Exercises 212
Programming Exercises 214
The Java Collections
Framework 133 Programming Project 5.1: Iterative Version of the
Towers of Hanoi 219
Chapter Objectives 133
Programming Project 5.2: Eight Queens 221
4.1 Collections 133
Programming Project 5.3: A Knight’s Tour 222
4.1.1 Collection Classes 134
4.1.2 Storage Structures for Collection Programming Project 5.4: Sudoku 225
Classes 136 Programming Project 5.5: Numbrix 227
CONTENTS xi

CHAPTER 6 7.3 Doubly-Linked Lists 281


7.3.1 A User’s View of the LinkedList
Array-Based Lists 233 Class 282
7.3.2 The LinkedList Class versus the
Chapter Objectives 233 ArrayList Class 282
6.1 The List Interface 234 7.3.3 LinkedList Iterators 285
6.2 The ArrayList Class 234 7.3.4 A Simple Program that uses a
6.2.1 Method Specifications for the LinkedList Object 291
ArrayList Class 235 7.3.5 Fields and Heading of the
6.2.2 A Simple Program with an LinkedList Class 294
ArrayList Object 244 7.3.6 Creating and Maintaining a
6.2.3 The ArrayList Class’s Heading and LinkedList Object 296
Fields 246 7.3.7 Definition of the Two-Parameter add
6.2.4 Definition of the One-Parameter add Method 298
Method 248 7.4 Application: A Line Editor 300
6.3 Application: High-Precision Arithmetic 251 7.4.1 Design and Testing of the Editor
6.3.1 Method Specifications and Testing of Class 304
the VeryLongInt Class 252 7.4.2 Method Definitions for the Editor
6.3.2 Fields in the VeryLongInt Class 308
Class 253 7.4.3 Analysis of the Editor Class
6.3.3 Method Definitions of the Methods 312
VeryLongInt Class 254 7.4.4 Design of the EditorUser
Summary 257 Class 312
Crossword Puzzle 258 7.4.5 Implementation of the EditorUser
Concept Exercises 259 Class 313
Programming Exercises 259 Summary 315
Programming Project 6.1: Expanding the Crossword Puzzle 316
VeryLongInt Class 263 Concept Exercises 317
Programming Project 6.2: An Integrated Web Programming Exercises 318
Browser and Search Engine, Part 2 264 Programming Project 7.1: Expanding the
SinglyLinkedList Class 320
Programming Project 7.2: Implementing the
CHAPTER 7 remove() Method in
SinglyLinkedListIterator 322
Linked Lists 267
Programming Project 7.3: Making a Circular
Chapter Objectives 267 Singly Linked List Class 322
7.1 What is a Linked List? 267 Programming Project 7.4: Alternative
7.2 The SinglyLinkedList Class—A Implementation of the LinkedList
Singly-Linked, Toy Class! 268 Class 323
7.2.1 Fields and Method Definitions in the Programming Project 7.5: Expanding the Line
SinglyLinkedList Class 273 Editor 323
7.2.2 Iterating through a Programming Project 7.6: An Integrated Web
SinglyLinkedList Object 276 Browser and Search Engine, Part 3 328
xii CONTENTS

CHAPTER 8 9.4 External Path Length 385


9.5 Traversals of a Binary Tree 386
Stacks and Queues 329 Summary 393
Chapter Objectives 329 Crossword Puzzle 394
8.1 Stacks 329 Concept Exercises 395
8.1.1 The Stack Class 329
8.1.2 A Fatal Flaw? 333
8.1.3 Stack Application 1: How Compilers
Implement Recursion 334
CHAPTER 10
Binary Search Trees 401
8.1.4 Stack Application 2: Converting from
Infix to Postfix 338 Chapter Objectives 401
8.1.5 Prefix Notation 343 10.1 Binary Search Trees 402
8.2 Queues 347 10.1.1 The BinarySearchTree
8.2.1 The Queue Interface 348 Implementation of the Set
8.2.2 Implementations of the Queue Interface 403
Interface 349 10.1.2 Implementation of the
8.2.3 Computer Simulation 350 BinarySearchTree Class 411
8.2.4 Queue Application: A Simulated Car 10.2 Balanced Binary Search Trees 430
Wash 351 10.2.1 AVL Trees 435
Summary 365 10.2.2 The Height of an AVL Tree 436
10.2.3 The AVLTree Class 438
Crossword Puzzle 366 10.2.4 Runtime Estimates 441
Concept Exercises 367 Summary 442
Programming Exercises 368 Crossword Puzzle 443
Programming Project 8.1: Making the Speedo’s Concept Exercises 444
Car Wash Simulation More Realistic 369
Programming Exercises 448
Programming Project 8.2: Design, Test, and
Programming Project 10.1: An Alternate
Implement a Program to Evaluate a
Implementation of the Binary-Search-Tree
Condition 371
Data Type 449
Programming Project 8.3: Maze-Searching,
Programming Project 10.2: Printing a
Revisited 374
BinarySearchTree Object 451
Programming Project 8.4: Fixing the Stack
Programming Project 10.3: The
Class 375
fixAfterInsertion Method 451
Programming Project 10.4: The
fixAfterDeletion Method 455

CHAPTER 9
Binary Trees 377
Chapter Objectives 377
CHAPTER 11
Sorting 457
9.1 Definition of Binary Tree 377
9.2 Properties of Binary Trees 378 Chapter Objectives 457
9.3 The Binary Tree Theorem 383 11.1 Introduction 457
CONTENTS xiii

11.2 Simple Sorts 458 12.5 The TreeSet Class 525


11.2.1 Insertion Sort 459 12.5.1 Implementation of the TreeSet
11.2.2 Selection Sort 461 Class 528
11.2.3 Bubble Sort 463 12.5.2 Application: A Simple Spell
11.3 The Comparator Interface 465 Checker 530
11.4 How Fast Can we Sort? 468 Summary 536
11.4.1 Merge Sort 470 Crossword Puzzle 537
11.4.2 The Divide-and-Conquer Design Concept Exercises 538
Pattern 476
Programming Exercises 539
11.4.3 Quick Sort 477
Programming Project 12.1: Spell Check,
11.5 Radix Sort 489
Revisited 540
Summary 493
Programming Project 12.2: Word
Crossword Puzzle 494 Frequencies 542
Concept Exercises 495 Programming Project 12.3: Building a
Programming Exercises 497 Concordance 543
Programming Project 11.1: Sorting a File into Programming Project 12.4: Approval Voting 545
Ascending Order 497 Programming Project 12.5: An Integrated Web
Browser and Search Engine, Part 4 548

CHAPTER 12
Tree Maps and Tree Sets 501 CHAPTER 13
Priority Queues 551
Chapter Objectives 501
12.1 Red-Black Trees 501 Chapter Objectives 551
12.1.1 The Height of a Red Black 13.1 Introduction 551
Tree 503 13.2 The PriorityQueue Class 552
12.2 The Map Interface 504 13.3 Implementation Details of the
12.3 The TreeMap Implementation of the PriorityQueue Class 553
SortedMap Interface 509 13.3.1 Fields and Method Definitions in
12.3.1 The TreeMap Class’s Fields and the PriorityQueue Class 557
Embedded Entry Class 512 13.4 The heapSort Method 567
12.3.2 Method Definitions in the TreeMap 13.4.1 Analysis of heapSort 572
Class 513 13.5 Application: Huffman Codes 573
12.4 Application of the TreeMap Class: a Simple 13.5.1 Huffman Trees 575
Thesaurus 517 13.5.2 Greedy Algorithm Design
12.4.1 Design, Testing, and Implementation Pattern 578
of the Thesaurus Class 518 13.5.3 The Huffman Encoding
12.4.2 Design and Testing of the Project 578
ThesaurusUser Class 521 Summary 590
12.4.3 Implementation of the Crossword Puzzle 591
ThesaurusUser Class 523 Concept Exercises 592
xiv CONTENTS

Programming Exercises 594 Programming Project 14.2: An Integrated Web


Browser and Search Engine, Part 6 640
Programming Project 13.1: Decoding a
Huffman-Encoded Message 595
Programming Project 13.2: An Integrated Web
Browser and Search Engine, Part 5 597 CHAPTER 15
Graphs, Trees, and Networks 643
Chapter Objectives 643
CHAPTER 14 15.1 Undirected Graphs 643
Hashing 599 15.2 Directed Graphs 647
Chapter Objectives 599 15.3 Trees 648
14.1 A Framework to Analyze Searching 599 15.4 Networks 649
14.2 Review of Searching 600 15.5 Graph Algorithms 650
14.2.1 Sequential Search 600 15.5.1 Iterators 650
14.2.2 Binary Search 601 15.5.2 Connectedness 658
14.2.3 Red-Black-Tree Search 602 15.5.3 Generating a Minimum Spanning
14.3 The HashMap Implementation of the Map Tree 659
Interface 603 15.5.4 Finding the Shortest Path through a
Network 663
14.3.1 Hashing 604
15.5.5 Finding the Longest Path through a
14.3.2 The Uniform Hashing
Network? 667
Assumption 609
14.3.3 Chaining 609 15.6 A Network Class 669
14.3.4 Implementation of the HashMap 15.6.1 Method Specifications and Testing
Class 612 of the Network Class 671
14.3.5 Analysis of the containsKey 15.6.2 Fields in the Network Class 680
Method 614 15.6.3 Method Definitions in the Network
14.3.6 The HashIterator Class 615 Class 681
14.3.7 Creating a Symbol Table by 15.7 Backtracking Through A Network 686
Hashing 617 Summary 689
14.4 The HashSet Class 625 Crossword Puzzle 690
14.5 Open-Address Hashing (optional) 626 Concept Exercises 691
14.5.1 The remove Method 627 Programming Exercises 693
14.5.2 Primary Clustering 631 Programming Project 15.1: The Traveling
14.5.3 Double Hashing 632 Salesperson Problem 694
Summary 635 Programming Project 15.2: Backtracking through a
Crossword Puzzle 636 Network 695
Concept Exercises 637 Programming Project 15.3: Determining Critical
Programming Exercises 639 Activities in a Project Network 697
Programming Project 14.1: The Double Hashing Programming Project 15.4: An Integrated Web
Implementation of the HashMap Class 640 Browser and Search Engine, Part 7 698
CONTENTS xv

APPENDIX 1 APPENDIX 3
Additional Features of the JAVA Choosing a Data Structure 721
Collections Framework 701
A3.1 Introduction 721
A1.1 Introduction 701 A3.2 Time-Based Ordering 721
A1.2 Serialization 701 A3.3 Index-Based Ordering 721
A1.3 Fail-Fast Iterators 703 A3.4 Comparison-Based Ordering 722
A3.5 Hash-Based Ordering 723
A3.6 Space Considerations 723
APPENDIX 2 A3.7 The Best Data Structure? 724
Mathematical Background 705
A2.1 Introduction 705
References 725
A2.2 Functions and Sequences 705
A2.3 Sums and Products 706 Index 727
A2.4 Logarithms 707
A2.5 Mathematical Induction 708
A2.6 Induction and Recursion 719
Concept Exercises 719
This page intentionally left blank
PREFACE

This book is intended for an object-oriented course in data structures and algorithms. The implementation
language is Java, and it is assumed that students have taken a first course in programming, not necessarily
in Java. That course should have covered the fundamental statements and data types, as well as arrays.
Chapter 0 supplies the material on Java that is fundamental to the remaining chapters, so it serves as a
review for those with previous experience in Java, and brings Java novices up to speed.

WHAT’S NEW IN THE THIRD EDITION


This edition presents two major changes from the second edition. First, the Scanner class has replaced
the BufferedReader and StringTokenizer classes. The Scanner class’s versatility supports pattern
matching as well as keyboard input and file input. Second, there is an increased emphasis on testing. In
particular, the unit-testing features of JUnit 4 are introduced in Chapter 2 and integrated in applications
throughout the remaining chapters.

THE JAVA COLLECTIONS FRAMEWORK


One of the distinctive features of this text is its emphasis on the Java Collections Framework, part of
the java.util package. Basically, the framework is a hierarchy with interfaces at each level except the
lowest, and collection classes that implement those interfaces at the lowest level. The collection classes
implement most of the data structures studied in a second computer-science course, such as a resizable array
class, a linked-list class, a stack class, a queue class, a balanced binary-search-tree class, a priority-queue
class, and a hash-map class.
There are several advantages to using the Java Collections Framework. First, students will be working
with code that has been extensively tested; they need not depend on modules created by the instructor or
textbook author. Second, the framework is available for later courses in the curriculum and beyond. Third,
although the primary emphasis is on using the Java Collections Framework, the framework classes are not
treated simply as “black boxes.” For each such class, the heading and fields are provided, and one method
definition is dissected. This exposition takes away some of the mystery that would otherwise surround the
class, and allows students to see the efficiency and succinctness of professionals’ code.
The version of the Java Collections Framework we will be working with includes type parameters.
Type parameters, sometimes called “generic types,” “generics,” or “templates,” were added to the Java
language starting with Java 5.0. With type parameters, there is no need to downcast the return value from
a collection, and many errors can be detected at compile-time that previously were discoverable only at
run-time.
To complement generics, three other features have been added: boxing, unboxing, and an enhanced
for statement. The elements in generic collections must be objects, often from a wrapper class such as
Integer. If a primitive value appears where a collection method requires a wrapper element as an argu-
ment, boxing automatically converts the primitive value to the corresponding wrapper element. Conversely,
xvii
xviii PREFACE

if a wrapper-class element appears where a primitive value is needed, unboxing automatically converts
that element to the corresponding primitive value. Finally, the enhanced for statement—often called a
“for-each” statement—has a sleek structure for iterating through a collection. The net effect of these new
features of Java is to improve productivity by relegating to the compiler many of the “boiler-plate” details
related to casting and iterating.

OTHER IMPLEMENTATIONS CONSIDERED


As important as the Java Collections Framework implementations are, they cannot be the exclusive focus
of such a fundamental course in data structures and algorithms. Approaches that differ from those in the
framework deserve consideration. For example, the HashMap class utilizes chaining, so there is a separate
section on open addressing, and a discussion of the trade-offs of one design over the other. Also, there is
coverage of data structures (such as a weighted digraph class) and algorithms (such as Heap Sort) that are
not yet included in the Java Collections Framework.
Sometimes, the complexity of the framework classes is mitigated by first introducing simpler
versions of those classes. For example, the SinglyLinkedList class—not in the Java Collections
Framework—helps to pave the way for the more powerful LinkedList class, which is in the framework.
And the BinarySearchTree class prepares students to understand the framework’s TreeMap class,
based on red-black trees.
This text satisfies another important goal of a data structures and algorithms course: Students have the
opportunity to develop their own data structures. There are programming projects in which data structures
are either created “from the ground up” or extended from examples in the chapters. And there are many
other projects to develop or extend applications that use the Java Collections Framework.

JUNIT AND TEST-FIRST DEVELOPMENT


Students realize that methods with no compile-time errors may still be a long way from correct, but they
often need help in learning how to systematically test their methods. As described in Chapter 2, JUnit is
an Open Source platform for the testing of units, that is, methods. For example, to test a findMedian
method, a FindMedianTest class is developed. The FindMedianTest class consists mainly of methods
that test findMedian. When all the test methods in FindMedianTest have been passed, the student’s
confidence in the correctness of findMedian is increased.
Instead of writing the tests after a method has been defined, we employ a “test-first” strategy. As
soon as a method’s specifications have been written, the tests for that method are coded. This ensures
that the tests are based on the specifications only, not on the definition of the method. These tests are run
on a “stub” version of the method to be tested, and all of the tests will fail. Then the method definition
is written, and the tests are run on that version of the method. Corrections to the method are made as
necessary until, eventually, all tests succeed. The test-first paradigm is introduced in Chapter 2 and utilized
in subsequent chapters.

PEDAGOGICAL FEATURES
This text offers several features that may improve the teaching environment for instructors and the learning
environment for students. Each chapter starts with a list of objectives, and most chapters conclude with
several major programming assignments. Each chapter also has a crossword puzzle, from Crossword
PREFACE xix

Weaver—to help students learn the key words and phrases in an enjoyable setting—and a variety of
exercises. The answers to all of the exercises are available to the instructor.
Each data structure is carefully described, with the specifications for each method given in javadoc
notation. Also, there are examples of how to call the method, and the results of that call. To reinforce
the important aspects of the material and to hone students’ coding skills in preparation for programming
projects, there is a suite of 23 lab experiments. The organization of these labs is described later in this
preface.

SUPPORT MATERIAL
The website for all of the support material is www.wiley.com/college/collins/
That website has links to the following information for students:
• The suite of 23 labs. Lab 0 starts with a brief overview of the lab format.
• The source codes for all classes developed in the text.
• Applets for projects that have a strong visual component.
Additionally, instructors can obtain the following from the website:
• PowerPoint slides for each chapter (approximately 1500 slides).
• Answers to every exercise and lab experiment.

SYNOPSES OF THE CHAPTERS


Chapter 0 serves as an introduction to the Java language for those whose first course was in some other
language. For students who are already familiar with Java, the chapter consists mostly of review material,
but the treatment of the Scanner class is worth perusing.
Chapter 1 focuses on the fundamentals of object-oriented programming: encapsulation, inheritance
and polymorphism. For a concrete illustration of these topics, an interface is created and implemented, and
the implementation is extended. The relationship between abstract data types and interfaces is explored, as
is the corresponding connection between data structures and classes. The Universal Modeling Language
provides a design tool to depict the interrelationships among interfaces, classes and subclasses.
Chapter 2 introduces unit testing with the free package JUnit. This is a vital topic in programming,
so method testing—before the method is defined—is emphasized in virtually all subsequent applications,
programming assignments and lab experiments. The chapter also includes some additional features of the
Java language. For example, there are sections on exception handling, file output, and the Java Virtual
Machine. Also, there is a section on the Object class’s equals method, why that method should be
overridden, and how to accomplish the overriding.
Finally, Chapter 2 introduces a “theme” project: to develop an integrated web browser and search
engine. This project, based on a paper by Newhall and Meeden [2002], continues through six of the
remaining chapters, and clearly illustrates the practical value of understanding data structures. In the first
part of the project, students develop a graphical user interface—a version of this interface is available
to instructors who prefer to provide this part of the project to students. The remaining six parts involve
an ArrayList object, a LinkedList object, a TreeMap object, a PriorityQueue object, a HashMap
object, and a Digraph object.
xx PREFACE

Chapter 3, Analysis of Algorithms, starts by defining functions to estimate a method’s execution-time


requirements, both in the average and worst cases. Big-O notation provides a convenient tool for estimating
these estimates. Because Big-O notation yields environment-independent estimates, these results are then
compared with actual run-times, which are determined with the help of the Random class and the nanoTime
method.
Chapter 4 outlines the Java Collections Framework. We start with some preliminary material
on collection classes in general, type parameters and the iterator design-pattern. The remainder of the
chapter presents part of the major interface hierarchy (Collection and List) and its implementations
(ArrayList and LinkedList).
Chapter 5, on recursion, represents a temporary shift in emphasis from data structures to algorithms.
There is a gradual progression from simple examples (factorial and decimal-to-binary) to more powerful
examples (binary search and backtracking). The mechanism for illustrating the execution of recursive
methods is the execution frame. Backtracking is introduced, not only as a design pattern, but as another
illustration of creating polymorphic references through interfaces. And the same BackTrack class is used
for maze-searching and solving eight queens, knight’s tour, Sudoku, and Numbrix.
In Chapter 6, we study the Java Collections Framework’s ArrayList class. An ArrayList object
is a smart array: automatically resizable, and with methods to handle insertions and deletions at any
index. The design starts with the method specifications for some of the most widely-used methods in the
ArrayList class. There follows a brief outline of the implementation of the class. The application of the
ArrayList class, high-precision arithmetic, is essential for public-key cryptography. This application is
extended in a lab and in a programming project. Several JUnit 4 tests are included in the chapter, and the
remaining tests are available from the book’s website.
Chapter 7 presents linked lists. A discussion of singly-linked lists leads to the development of a prim-
itive SinglyLinkedList class. This serves mainly to prepare students for the framework’s LinkedList
class. LinkedList objects are characterized by linear-time methods for inserting, removing or retrieving
at an arbitrary position. This property makes a compelling case for list iterators: objects that traverse a
LinkedList object and have constant-time methods for inserting, removing or retrieving at the “current”
position. The framework’s design is doubly-linked and circular, but other approaches are also considered.
The application is a small line-editor, for which list iterators are well suited. Testing entails an interesting
feature: the testing of protected methods. The line-editor application is extended in a programming project.
Stacks and queues are the subjects of Chapter 8. The framework’s Stack class has the expected push,
pop, and peek methods. But the Stack class also allows elements to be inserted or removed anywhere
in a Stack object, and this permission violates the definition. Students can use the Stack class—with
care—or develop their own version that satisfies the definition of a stack. There are two applications of
stacks: the implementation of recursion by a compiler, and the conversion from infix to postfix. This latter
application is expanded in a lab, and forms the basis for a project on evaluating a condition.
The Java Collections Framework has a Queue interface, but that interface supports the removal of
any element from a queue! As with the Stack class, students can tolerate this flaw and use a class—such
as LinkedList —that implements the Queue interface. Or they can create their own implementation
that does not violate the definition of a queue. The specific application of queues, calculating the average
waiting time at a car wash, falls into the general category of computer simulation.
Chapter 9 focuses on binary trees in general, as a prelude to the material in Chapters 10 through
13. The essential features of binary trees are presented, including both botanical (root, branch, leaf) and
familial (parent, child, sibling) terms. Binary trees are important for understanding later material on AVL
trees, decision trees, red-black trees, heaps, and Huffman trees.
PREFACE xxi

In Chapter 10, we look at binary search trees, including a BinarySearchTree class, and explain the
value of balanced binary search trees. Rotations are introduced as the mechanism by which re-balancing
is accomplished, and AVL trees are offered as examples of balanced binary search trees. An AVLTree
class, as a subclass of BinarySearchTree, is outlined; the crucial methods, fixAfterInsertion and
fixAfterDeletion, are left as programming projects.
Sorting is the theme of Chapter 11. Estimates of the lower bounds for comparison-based sorts are
determined. A few simple sorts are defined, and then we move on to two sort methods provided by the
framework. Quick Sort sorts an array of a primitive type, and Merge Sort works for an array of objects
and for implementations of the List interface. A lab experiment compares all of these sort algorithms on
randomly-generated integers.
The central topic of Chapter 12 is how to use the TreeMap class. A map is a collection in which
each element has a unique key part and also a value part. In the TreeMap implementation of the Map
interface, the elements are stored in a red-black tree, ordered by the elements’ keys. There are labs to
guide students through the details of re-structuring after an insertion or removal. The application consists
of searching a thesaurus for synonyms, and JUnit 4 testing is again illustrated. The TreeSet class has a
TreeMap field in which each element has the same, dummy value-part. The application of the TreeSet
class is a simple spell-checker, which is also thoroughly tested.
Chapter 13 introduces the PriorityQueue class. This class is part of the Java Collections Frame-
work and, like the Stack class and Queue interface in Chapter 8, allows methods that violate the definition
of a priority queue. The class utilizes a heap to provide insertions in constant average time, and removal of
the smallest-valued element in logarithmic worst time. The application is in the area of data compression:
Given a text file, generate a minimal, prefix-free encoding. There is a project assignment to convert the
encoded message back to the original text file.
Chapter 14 investigates hashing. The Java Collections Framework has a HashMap class for elements
that consist of unique-key/value pairs. Basically, the average time for insertion, removal, and searching is
constant! This average speed is exploited in an application (and JUnit 4 tests) to create a simple symbol
table. The Java Collections Framework’s implementation of hashing, using chained hashing, is compared
to open-address hashing.
The most general data structures—graphs, trees, and networks—are presented in Chapter 15. There
are outlines of the essential algorithms: breadth-first traversal, depth-first traversal, finding a minimum
spanning tree, and finding the shortest or longest path between two vertices. The only class developed
is the (directed) Network class, with an adjacency-map implementation. Other classes, such as Undi
rectedGraph and UndirectedNetwork, can be straightforwardly defined as subclasses of Network.
The Traveling Salesperson Problem is investigated in a lab, and there is a programming project to solve
that problem—not necessarily in polynomial time! Another backtracking application is presented, with the
same BackTrack class that was introduced in Chapter 5.
The website includes all programs developed in each chapter, all JUnit 4 tests, and applets, where
appropriate, to animate the concepts presented.

APPENDIXES
Appendix 1 has two additional features of the Java Collections Framework. Each of the collection classes in
the framework is serializable, that is, an instance of the class can be conveniently stored to an output stream,
and the instance can later be re-constituted from an input stream (de-serialization). Framework iterators
are fail-fast: During an iteration through a collection, there should be no insertions into or removals from
xxii PREFACE

the collection except by the iterator. Otherwise, the integrity of that iterator may be compromised, so an
exception will be thrown as soon as the iterator’s unreliability has been established.
Appendix 2 contains the background that will allow students to comprehend the mathematical aspects
of the chapters. Summation notation and the rudimentary properties of logarithms are essential, and the
material on mathematical induction will lead to a deeper appreciation of recursion as well as the analysis
of binary trees.
Appendix 3, “Choosing a Data Structure,” can be viewed as a summary of the eight major data
structures in the book. These collection classes are categorized according to their ordering of elements (for
example, time-based for stacks and queues) and according to their performance of standard operations (for
example, the TreeMap class requires logarithmic-in-n time to search for a key). Table A3.1 summarizes
the summary.

ORGANIZATION OF THE LABS


There are 23 web labs associated with this text. For both students and instructors, the initial Uniform
Resource Locator (URL) is www.wiley.com/college/collins.
The labs do not contain essential material, but provide reinforcement of the text material. For example,
after the ArrayList and LinkedList classes have been investigated, there is a lab to perform some timing
experiments on those two classes.
The labs are self-contained, so the instructor has considerable flexibility in assigning the labs:
a. they can be assigned as closed labs;
b. they can be assigned as open labs;
c. they can be assigned as ungraded homework.
In addition to the obvious benefit of promoting active learning, these labs also encourage use of the
scientific method. Basically, each lab is set up as an experiment. Students observe some phenomenon,
such as creating a greedy cycle to solve the Traveling Salesperson Problem. They then formulate and
submit a hypothesis —with their own code—about the phenomenon. After testing and, perhaps, revising
their hypothesis, they submit the conclusions they drew from the experiment.

ACKNOWLEDGEMENTS
Joshua Bloch, lead designer of the Java Collections Framework, gave valuable insights on type parameters
and their impact on the Java Collections Framework.
Chun Wai Liew of Lafayette College helped to incorporate JUnit into this edition of the text.
I am indebted to the suggestions and corrections of the reviewers: Dean Hendrix (Auburn University),
Benjamin Kuperman (Oberlin College), Andrew Haas (State University of New York—Albany), Kathy
Liszka (University of Akron), Paul Bladek (Edmonds Community College), Siva Jasthi (Metropolitan State
University), Hashem Anwari (Northern Virginia Community College), Alan Peslak (Nova Southeastern
University), H. K. Dai (Oklahoma State University), Jiang Li (Austin Peay State University), Paul J.
Wagner (University of Wisconsin—Eau Claire), John Mallozzi (Iona College), Robert Goldberg (Queens
College), and Michael Clancy (University of California—Berkeley).
Introduction to Java CHAPTER 0

This is a book about programming: specifically, about understanding and using data structures and
algorithms. The Java Collections Framework has a considerable number of data structures and
algorithms. Subsequent chapters will focus on what the framework is and how to use the framework
in your programs. For this information to make sense to you, you will need to be familiar with certain
aspects of Java that we present in this chapter. All of the material is needed, either for the framework
itself or to enable you to use the framework in your programming projects.

CHAPTER OBJECTIVES
1. Learn (or review) the fundamentals of Java, including classes, objects and messages.
2. Be able to use javadoc in writing method specifications.
3. Incorporate the Scanner class into your programming.
4. Understand the significance of the fact that a copy of the argument is stored in the corre-
sponding parameter when a method is called.
5. Understand the details of arrays and output formatting.

0.1 Java Fundamentals


Every Java program is a collection of classes. Basically, a class consists of variables, called fields, together
with functions, called methods, that operate on those fields. A program is executed when a special method,
the main method, is called by the run-time system (also known as the Java Virtual Machine). The heading
of this method is fixed, as shown in the following program:
public class HelloWorld
{
public static void main (String [ ] args)
{
System.out.println ("Hello, world!");
} // method main
} // class HelloWorld

The main method in this program calls another method, println, to produce the following output to the
console window:
Hello, world!

1
2 CHAPTER 0 Introduction to Java

Console output, that is, output to the console window on your monitor, is handled by the methods
System.out.print, System.out.println, and System.out.printf (see Section 0.5).

0.1.1 Primitive Types


A primitive type is a collection of values, together with operations that can be performed on those values.
For example, the reserved word int denotes the primitive type whose values are integers in the range from
about −2 billion to 2 billion, and whose operations are addition, subtraction, and so on. A variable—also
called an instance—of type int is a location in computer memory that can hold one value of type int. The
term “variable” is used because the value stored can change during the execution of a program. Instead of
specifying the location’s address, we provide an identifier (that is, a name) and the Java compiler associates
the identifier with a location. For example, here is a declaration for an int variable whose identifier is
score:

int score;

By a standard abuse of language, we say that score is a variable instead of saying that score is an
identifier for a variable. An assignment statement allows us to store a value in a variable. For example,
score = 0;

stores the value 0 in the variable score. A subsequent assignment can change the value stored:
score = 88;

The left-hand side of an assignment statement must be a variable, but the right-hand side can be an arbitrary
expression: any legal combination of symbols that has a value. For example, we can write
score = (score + 3) / 10;

If score had the value 88 prior to the execution of this assignment statement, then after its execution, score
would have the value 9. Note that the division operator, /, returns the result of integer division because
the two operands, 91 and 10, are both integers.
Another operator in the int type is %, the modulus operator, which returns the integer remainder
after integer division. For example, 91 % 10 returns the remainder, 1, when 91 is divided by 10. Similarly,
87 % 2 returns 1, (−37) % 5 returns −2, and 10 % 91 returns 10.
Java supports eight primitive types, summarized in Table 0.1.

0.1.2 The char Type


The char type stores characters in the Unicode collating sequence, which includes all of the ASCII
characters such as ‘a’, ‘A’, ‘?’, and ‘ ’, the blank character. For example, suppose we write
char delimiter = ' ';

Then delimiter is a variable of type char and contains the value ' '. The Unicode collating sequence
also includes other—that is, non-Roman, alphabets—such as Greek, Cyrillic, Arabic, and Hebrew. The
Unicode collating sequence holds up to 65,536 (= 216 ) distinct characters, but only about half of them have
been assigned as of now. To include a character such as ☺ in a program, you provide an escape sequence:
0.2 Classes 3

Table 0.1 The Primitive Types

Primitive Type Range Size

int −2,147,483,648 to 2,147,483,647 4 bytes


long –263 to 263 −1 8 bytes
short −128 to 127 2 bytes
byte −64 to 63 1 byte
double −1.7976931348623157 * 10308 to 8 bytes
1.7976931348623157 * 10308
(15 digits of precision)
float −3.4028235 * 1038 to 4 bytes
3.4028235 * 1038
(6 digits of precision)
char 2 bytes
boolean false, true 1 byte

a sequence of symbols that starts with the backslash character, ‘\’ and designates a single character. For
example, the escape sequence for the smiley-face character, ☺, is ‘\u263A’, so we can write
char c = '\u263A';

to declare a char variable c and assign the smiley-face character to c.


More importantly, escape sequences are used for print control. For example, ‘\n’ represents the
new-line character and ‘\t’ represents the tab character. The execution of
System.out.println ("We can control\n\noutput with \tprint-control\t\t characters");

will produce output of


We can control

output with print-control characters

An escape sequence is also needed to print a double quote—otherwise, the double quote would signify
the end of the string to be output. For example, the execution of
System.out.println ("His motto was \"Don't sweat the nickels and dimes!\"");

will produce output of


His motto was "Don't sweat the nickels and dimes!"

0.2 Classes
In addition to primitive types such as int and char, Java provides programmers with the ability to create
powerful new types called “classes.” Given a problem, we develop classes—or utilize already existing
classes—that correspond to components of the problem itself. A class combines the passive components
(fields) and active components (methods) into a single entity. This grouping increases program modularity:
4 CHAPTER 0 Introduction to Java

the separation of a program into components that are coherent units. Specifically, a class is isolated from
the rest of the program, and that makes the whole program easier to understand and to modify.
In Section 0.2.1, we investigate the class concept in more detail by looking at a specific example:
the String class, the most widely used of Java’s pre-declared classes.

0.2.1 The String Class


To start with a simple example, we consider the String class. Actually, the String class is somewhat
intricate, with several fields and dozens of methods. But as we will focus on using the String class, we
will ignore the fields, and look at only a few of the methods. In Chapter 1, we will introduce a new class
and investigate its fields as well as its methods.
An object is an instance of a class; in other words, an object is a variable that contains fields and
can call methods. In the context of using the String class, an object can be thought of as a variable that
contains a string —a sequence of characters—and can call the String class’s methods. This gives rise to
two questions:
1. How are String objects declared?
2. How do String objects call String methods?
The answer to the first question is somewhat surprising: String objects, in fact, objects of any class,
cannot be declared in Java. Instead, we declare variables, called reference variables, that can contain the
address of an object. For example, we can declare
String s1;

Then s1 is not a String object, but a variable that can contain the address of a String object.1 In order
for s1 to actually contain such a reference, the space for a String object must be allocated, then the fields
in that newly created String object must be initialized, and finally, the address of that String object
must be assigned to s1. We combine these three steps into a single assignment statement. For example, if
we want s1 to be a reference to an empty String object, we write:
s1 = new String();

The right-hand side of this assignment statement accomplishes several tasks. The new operator allocates
space in memory for a String object, calls a special method known as a “constructor” to initialize the
fields in the object, and returns the address of that newly created object; that address is assigned to s1. A
constructor is a method whose name is the same as the class’s name and whose purpose is to initialize
the object’s fields. In this example, the fields are initialized to the effect that the newly created String
object represents an empty string, that is, a string that contains no characters.
The constructor just mentioned has no parameters, and is called the default constructor. The String
class also has a constructor with a String-reference parameter. Here is the heading of that constructor:
public String (String original)

The parameter original is of type reference-to-String. When this constructor is called, the
argument—inside the parentheses—will be assigned to the parameter, and then the body of the
constructor (the statements inside the braces) will be executed. For an example of a call to this

1 In the languages C and C++, a variable that can contain the address of another variable is called a pointer variable.
0.2 Classes 5

constructor, the following statement combines the declaration of a reference variable and the assignment
to that variable of a reference to a newly constructed String object:
String s2 = new String ("transparent");

When this statement is executed, the space for a new String object is allocated, the fields in that
newly created String object are initialized to the effect that the new String object represents the string
"transparent", and the address of that new String object is assigned to the String reference s2.
Now that s1 and s2 contain live references, the objects referenced by s1 and s2 can invoke
any String method.2 For example, the length method takes no parameters and returns the number of
characters in the calling object, that is, the object that invokes the length method. We can write
System.out.println (s1.length());

The output will be 0. If, instead, we write


System.out.println (s2.length());

then the output will be 11 because the calling object contains the string "transparent".
The default constructor and the constructor with a String-reference parameter have the same name,
String, but have different parameter lists. Java allows method overloading: the ability of a class to have
methods with the same method identifier but different parameter lists. In order to clarify exactly what
method overloading entails, we define a method’s signature to consist of the method identifier together
with the number and types of parameters, in order. Method overloading is allowed for methods with
different signatures. For example, consider the following method headings:
public String findLast (int n, String s)

public String findLast (String s, int n)

In this example, the first method’s parameter list starts with an int parameter, but the second method’s
parameter list starts with a String parameter, so the two methods have different signatures. It is legal for
these two methods to be defined in the same class; that is, method overloading is permitted. Contrast this
example with the following:
public String findLast (int n, String s)

public int findLast (int j, String t)

Here the two methods have the same signature—notice that the return type is irrelevant in determining
signature—so it would be illegal to define these two methods in the same class.

0.2.2 Using javadoc Notation for Method Specifications


The String class has a method that returns a copy of a specified substring—a contiguous part of—the
calling string object. To make it easier for you to understand this method, we will supply the method’s
specification. A method specification is the explicit information a user will need in order to write code
that invokes the method.

2 Except String constructors, which are invoked by the new operator. For that reason, and the fact that constructors do not have a return

type, the developers of the Java language do not classify a constructor as a method (see Arnold, 1996). But for the sake of simplicity, we
lump constructors in with the methods of a class.
6 CHAPTER 0 Introduction to Java

The method specification will include javadoc notation. javadoc is a program that converts Java
source code and a specially formatted block of comments into Application Programming Interface (API)
code in Hypertext Markup Language (HTML) for easy viewing on a browser. Because javadoc is available
on any system that has Java, javadoc format has become the standard for writing method specifications.
Each comment block starts with “/**”, each subsequent line starts with “*”, and the final line in a block
has “*/”. The complete specification consists of the javadoc comments and the method heading:
/**
* Returns a copy of the substring, between two specified indexes, of this String
* object.
*
* @param beginIndex – the starting position (inclusive) of the substring.
* @param endIndex – the final position (exclusive) of the substring.
*
* @return the substring of this String object from indexes beginIndex (inclusive)
* to endIndex (exclusive).
*
* @throws IndexOutOfBoundsException – if beginIndex is negative, or if
* beginIndex is greater than endIndex, or if endIndex is greater than
* length().
*
*/
public String substring (int beginIndex, int endIndex)

The first sentence in a javadoc comment block is called the postcondition: the effect of a legal call to
the method. The comment block also indicates parameters (starting with @param), the value returned
(@return), and what exceptions can be thrown (@throws). An exception, such as IndexOutOfBounds
Exception, is an object created by an unusual condition, typically, an attempt at invalid processing.
Section 2.2 covers the topic of exceptions, including how they are thrown and how they are caught. To
avoid confusing you, we will omit @throws comments for the remainder of this chapter.
To illustrate the effect of calls to this method, here are several calls in which the calling object is
either an empty string referenced by s1 or the string “transparent” referenced by s2:
s1.substring (0, 0) // returns reference to an empty string
s1.substring (0, 1) // error: 2nd argument > length of calling object
s2.substring (1, 4) // returns reference to copy of "ran", a 3-character string
s2.substring (5, 10) // returns reference to copy of "paren", a 5-character string
s2.substring (5, 11) // returns reference to copy of "parent", a 6-character string

There are several points worth mentioning about the comment block. In the postcondition and elsewhere,
“this String object” means the calling object. What is returned is a reference to a copy of the substring.
And the last character in the designated substring is at endIndex -1, not at endIndex.
The javadoc comment block just given is slightly simpler than the actual block for this substring
method in the String class. The actual javadoc comment block includes several html tags: <pre>,
<blockquote>, and <code>. And if you viewed the description of that method from a browser—that is,
after the javadoc program had been executed for the String class—you would see the comments in an
easier-to-read format. For example, instead of
0.2 Classes 7

* @return the substring of this String object from indexes beginIndex (inclusive)
* to endIndex (exclusive).

you would see

Returns:
the substring of this String object from indexes beginIndex (inclusive)
to endIndex (exclusive).

The on-line Java documentation is generated with javadoc. And the documentation about a method in one
class may include a hyperlink to another class. For example, the heading for the next() method in the
Scanner class is given as

public String next()

So if you are looking at the documentation of the next() method and you want to see some information
on the String class, all you need to do is click on the String link.
Throughout the remainder of this text, we will regularly use javadoc to provide information about a
method. You should try to use javadoc to describe your methods.

0.2.3 Equality of References and Equality of Objects


Reference variables represent an advance over the pointer mechanism of Java’s predecessors, C and C++.
A pointer variable could be assigned any memory address, and this often led to hard-to-find errors. In
contrast, if a reference variable contains any address, it must be the address of an object created by the new
operator. To indicate that a reference variable does not contain an address, we can assign to that variable
a special value, indicated by the reserved word null:
String s3 = null;

At this point, s3 does not contain an address, so it would be illegal to write


s3.length()

In object-oriented parlance, when a method is invoked, a message is being sent to the calling object.
The term “message” is meant to suggest that a communication is being sent from one part of a program
to another part. For example, the following message returns the length of the String object referenced
by s2:
s2.length()

This message requests that the object referenced by s2 return its length, and the value 11 is returned.
The form of a message consists of a reference followed by a dot—called the member-selection opera-
tor —followed by a method identifier followed by a parenthesized argument list.
Make sure you understand the difference between a null reference (such as s3), and a reference
(such as s1) to an empty string. That distinction is essential to an understanding of Java’s object-reference
model.
The distinction between objects and references is prominent in comparing the equals method and
the == operator. Here is the method specification for equals:
/**
* Compares this String object to a specified object:
8 CHAPTER 0 Introduction to Java

* The result is true if and only if the argument is not null and is a String object
* that represents the same sequence of characters as this String object.
*
* @param anObject - the object to compare this String against.
*
* @return true - if the two String objects are equal; false otherwise.
*
*/
public boolean equals (Object anObject)

The parameter’s type suggests that the calling object can be compared to an object of any type, not just
to a String object. Of course, false will be returned if the type is anything but String. The Object
class is discussed in Chapter 1.
The == operator simply compares two references: true is returned if and only if the two references
contain the same address. So if str1 and str2 are referencing identical String objects that are at different
addresses,
str1.equals (str2)

will return true because the String objects are identical, but
str1 == str2

will return false because the str1 and str2 contain different addresses.
Finally, you can create a String object without invoking the new operator. For example,
String str0 = "yes",
str3 = "yes";

Because the underlying strings are identical, only one String object is constructed, and both str0 and
str3 are references to that object. In such cases, we say that the String object has been interned .
Figure 0.1 has several examples, and contrasts the String method equals with the reference
operator ==.
The reason the output is different for the first and third calls to println in Figure 0.1 is that the
equals method compares strings and the == operator compares references. Recall that each time the new
operator is invoked, a new String object is created. So, as shown in Figure 0.2, s4 is a reference to

String s4 = new String ("restful"),


s5 = new String ("restful"),
s6 = new String ("peaceful"),
s7 = s4,
s8 = "restful",
s9 = "restful";

System.out.println (s4.equals (s5)); // the output is "true"


System.out.println (s4.equals (s6)); // the output is "false"
System.out.println (s4 == s5); // the output is "false"
System.out.println (s4 == s7); // the output is "true"
System.out.println (s4 == s8); // the output is "false"
System.out.println (s8 == s9); // the output is "true"
FIGURE 0.1 Illustration of the effect of the equals method and == operator
0.2 Classes 9

restful
s4

restful

s5

peaceful

s6

s7

s8
restful

s9

FIGURE 0.2 An internal view of the references and objects in Figure 0.1

a String object whose value is “restful”, and s5 is a reference to a different String object whose value
is also “restful”.

0.2.4 Local Variables


Variables declared within a method—including the method’s parameters—are called local variables. For
example, the following method has two local variables, n and j:
/**
* Determines if a specified integer greater than 1 is prime.
*
* @param n – the integer whose primality is being tested.
*
* @return true – if n is prime.
*
*/
public static boolean isPrime (int n)
{
if (n == 2)
return true;
if (n % 2 == 0)
return false;
10 C H A P T E R 0 Introduction to Java

for (int j = 3; j * j <= n; j = j + 2)


if (n % j == 0)
return false;
return true;
} // method isPrime

Local variables must be explicitly initialized before they are used. For example, suppose we have
public void run()
{
int k;

System.out.println (isPrime (k));


} // method run

Compilation will fail, with an error message indicating that “variable k might not have been initialized.”
The phrase “might not have been initialized” in the error message suggests that the compiler does not
perform a detailed analysis of the method’s code to determine if, in fact, the variable has been properly
initialized. For example, the same error message will be generated by the following method:
public void run()
{
int k;

boolean flag = true;

if (flag)
k = 20;
if (!flag)
k = 21;
System.out.println (isPrime (k));
} // method run

Clearly, if we look at this method as a whole, the variable k does receive proper initialization. But if
each statement is considered on its own, no such guarantee can be made. The following slight variant is
acceptable because the if-else statement is treated as a unit:
public void run()
{
int k;

boolean flag = true;

if (flag)
k = 20;
else
k = 21;
System.out.println (isPrime (k));
} // method run
0.2 Classes 11

The scope of an identifier is the region of a program to which that identifier’s declaration applies. In
the isPrime method, the scope of the parameter n is the entire function definition, but the scope of the
variable j is only the for statement. A compile-time error results if an attempt is made to access an
identifier outside of its scope: for example, if we tried to print out the value of j outside of the for
statement in the isPrime method. This restriction of identifiers to specific code segments—and not, for
example, to an entire method—promotes modularity.
To see how it is possible to declare the same identifier more than once in a class, we need to define
what a “block” is. A block is an enclosed sequence of declarations and/or statements enclosed in curly
braces { }. For a field identifier, its enclosing block is the entire class enclosed by the curly braces. It is
permissible to re-declare the field identifier within a method in the class. But it is illegal to re-declare
a local identifier within its block. Special case: for a variable identifier declared in the header of a for
statement, its scope is the entire for statement. So it is possible to have two for statements in the same
method with identical variable identifiers declared in the headers of those for statements (but that identifier
cannot also be declared outside of those for statements as a local variable of the method). The following
class illustrates the scopes of several identifiers.
public class Scope
{
boolean t = true;

int x = 99;

double sample = 8.1;

public void sample (double x)


{
double y = 5;

x = 5.3;
for (int t = 0; t < 3; t++)
{
int i = t + 4;

System.out.println (i + t + x);
} // end of int t’s scope; end of i’s scope

for (int t = 0; t < 7; t++)


x = t; // end of the scope of this version of int t
} // method sample; end of double x’s scope; end of y’s scope

public void original()


{
System.out.println (t + " " + x + " " + sample);
} // method original

} // class Scope; end of boolean t’s scope; end of int x’s scope; end of double sample’s scope

All three fields— t, x and sample —are re-declared within the method sample. But the scope of those
three fields includes the method original. And note that there is no ambiguity when sample is used
12 C H A P T E R 0 Introduction to Java

both as a field identifier and as a method identifier, because a method identifier is always followed by
parentheses.

0.2.5 The Scanner Class


One of the recent improvements in Java is provided by the Scanner class in java.util. A Scanner
object operates on text: a sequence of lines, separated by end-of-line markers. The text may be input from
the keyboard, input from a file, or a string. There are Scanner methods to return the rest of the current
line, to return the next primitive value, and to return the next string.
Let’s start with the three key constructors. Here is a declaration of a Scanner object that will read
input from the keyboard:
Scanner sc = new Scanner (System.in);

The following declares a Scanner object that will read from the file named “myFile.dat”:
Scanner scanner = new Scanner (new File ("myFile.dat"));

If, instead, we want to scan over the String object line, we can declare the following:
Scanner lineScanner = new Scanner (line);

We can now use the Scanner object sc declared above to read in an int value representing a test score:
int score = sc.nextInt( );

In order to understand how the nextInt method works, we need to introduce some terminology. A scanner
subdivides the text into tokens separated by delimiters. In the case of the nextInt method, the delimiters
are whitespace characters: blanks, end-of-line markers, newline characters, tabs, and so on. The tokens are
everything else. The scanning proceeds as follows: First, all whitespace is skipped over. Then the token is
read in. If the characters in the token represent an int value, that value is stored in the variable score.
In Section 2.2 of Chapter 2, there is a discussion of what happens if the token does not represent an int
value.
We can read in and add up scores until a sentinel of −1 is read. In the following program, we need
to utilize the class java.util.Scanner in the package java.util. Because we will often want several
classes from java.util, we specify that we want all of the classes from that package to be available.
How? By denoting java.util.* in the import directive, we notify the compiler that the entire package
java.util is to be made available.
In this program, and in all subsequent programs in this book, the main method consists of a single
line. A new instance of the class is created with a call to the class’s default constructor (automatically
supplied by the compiler), and this new instance invokes its run method. Here is the complete file:
import java.util.*; // for the Scanner class

public class Sum


{
public static void main (String[ ] args)
{
new Sum().run();
} // method main
0.2 Classes 13

public void run()


{
final int SENTINEL = -1;

final String INPUT_PROMPT = "\nPlease enter a test score (or " +


SENTINEL + " to quit): ";

final String SUM_MESSAGE = "\n\nThe sum of the scores is ";

Scanner sc = new Scanner (System.in);

int score,
sum = 0;

while (true)
{
System.out.print (INPUT_PROMPT);
score = sc.nextInt();
if (score == SENTINEL)
break;
sum += score;
} // while
System.out.println (SUM_MESSAGE + sum);
} // method run

} // class Sum

A noteworthy feature of this program is the structure of the while statement. The loop continues until
the sentinel is read in. The execution of the break statement causes an abrupt exit of the loop; the next
statement to be executed is the println that outputs the sum. The loop has only one entrance and only
one exit, and that helps us to understand the action of the loop. Also, there is only one place where the
prompt is printed, and only one place where input is read.
In that program, why did we use a sentinel instead of allowing the end user to terminate the loop
by not entering more values? When sc.next() is called, the program will pause until a non-whitespace
value is entered (followed by a pressing of the Enter key). In other words, a sentinel is needed to terminate
keyboard input. For scanning a line or a file, there will rarely be a sentinel, so a call to the next() method
should be preceded by a call to the Scanner class’s hasNext() method, which returns true if there is
still another token to be scanned in, and false otherwise. This will ensure that the call to next() will not
cause an abnormal termination due to the lack of a next token.
In the class Sum, the end-user was prompted to enter a single int value per line. In general, a
line may have several int values, or even no int values. For example, we could have the following:
Scanner sc = new Scanner (System.in);

int score1 = sc.nextInt(),


score2 = sc.nextInt(),
score3 = sc.nextInt();
14 C H A P T E R 0 Introduction to Java

Here is a sample sequence of lines, with the second line blank:

85
95 87

The variables score1, score2, and score3 will now have the values 85, 95, and 87, respectively.
For a slightly more complicated example, the following program reads from a file. Each line in the
file consists of a student’s name and grade point average. The output is the name of the student with the
highest grade point average. There is no sentinel. Instead, the scanning continues as long as the input file
has another token, that is, any sequence of characters excluding whitespace. As indicated previously, the
hasNext( ) method returns true if and only if there are any tokens remaining in the file. The next( )
method returns the next token as a string.
import java.util.*; // for the Scanner class

import java.io.*; // for the File class

public class HighestGPA


{
public static void main (String[ ] args) throws FileNotFoundException
{
new HighestGPA().run();
} // method main

public void run() throws FileNotFoundException


{
final double NEGATIVE_GPA = -1.0;

final String NO_VALID_INPUT =


"Error: the given file has no valid input.";

final String BEST_MESSAGE =


"\n\nThe student with the highest grade point average is ";

Scanner fileScanner = new Scanner (new File ("students.dat"));

String name,
bestStudent = null;

double gpa,
highestGPA = NEGATIVE_GPA;

while (fileScanner.hasNextLine())
{
Scanner lineScanner = new Scanner (fileScanner.nextLine());

name = lineScanner.next();
gpa = lineScanner.nextDouble();
if (gpa > highestGPA)
0.2 Classes 15

{
highestGPA = gpa;
bestStudent = name;
} // if
} // while
if (highestGPA == NEGATIVE_GPA)
System.out.println (NO_VALID_INPUT);
else
System.out.println (BEST_MESSAGE + bestStudent);
} // method run

} // class HighestGPA

The significance of the clause throws FileNotFoundException is explained in Section 2.3.3 of


Chapter 2. As described in Section 0.4, the variable bestStudent is initialized to avoid a “might not
have been initialized” error message when bestStudent is printed. Note, for example, that if the file
“students.dat” is empty, the loop will not be executed, and so bestStudent will not be assigned a value
in the loop.
Here are sample contents of the file “students.dat”:
Larry 3.3
Curly 3.7
Moe 3.2
The corresponding output is:
The student with the highest grade point average is Curly
In the above program, the name of the input file was “hard-wired,” that is, actually specified in the code.
It is more realistic for the end-user to enter, from the keyboard, the input-file path. Then we need two
scanner objects: one to read in the input-file path, and another to read the input file itself. Because a
file path may contain blank spaces, we cannot invoke the next() method to read in the input-file path.
Instead, we call the nextLine() method, which advances the scanner past the current line, and returns
(the remainder of) the current line, excluding any end-of-line marker. Here is the code that replaces the
declaration and assignment to fileScanner in that program:
final String IN_FILE_PROMPT = "Please enter the path for the input file: ";

Scanner keyboardScanner = new Scanner (System.in);

System.out.print (IN_FILE_PROMPT);

String inFileName = keyboardScanner.nextLine( );

Scanner fileScanner = new Scanner (new File (inFileName));

Here are sample input and output for the resulting program, with the input in boldface:
Please enter the path for the input file: students.dat

The student with the highest grade point average is Curly


16 C H A P T E R 0 Introduction to Java

Keep in mind that the next() method skips over whitespace and returns the next token, but the
nextLine() method skips past the current line, and returns that current line, excluding any end-of-line
marker. Similarly, the hasNext() method returns true if and only if there is another token in
the text, while the hasNextLine() method returns true if and only if there is at least one more
character—including whitespace—in the text. So if the text has a line of blanks remaining, or even an
extra end-of-line marker, hasNext() will return false, but hasNextLine( ) will return true.
The above example illustrates a pattern we will see over and over in the remaining chapters. A
keyboard scanner scans in the path of an input file, a file scanner scans in the lines in the file, and a line
scanner scans over a single line.
In the next example, a scanner retrieves each word in a line, and the word is converted to lower-case
and printed. The scanner is declared in a method whose only parameter is a line to be parsed into words:
public void run()
{
split ("Here today gone tomorrow");
} // method run

public void split (String line)


{
Scanner sc = new Scanner (line);

while (sc.hasNext())
System.out.println (sc.next().toLowerCase());
} // method split

The output will be

here
today
gone
tomorrow

Unfortunately, if the input contains any non-alphabetic, non-whitespace characters, those characters will
be included in the tokens. For example, if the call is
split ("Here today, gone tomorrow.");

The output will be

here
today,
gone
tomorrow.

We can override the default delimiter of whitespace with the useDelimiter (String pattern)
method, which returns a (reference to a) Scanner object. For example, if we want the delimiter to be
any positive number of non-alphabetic characters, we can explicitly indicate that as follows:
Scanner sc = new Scanner (line).useDelimiter ("[∧ a-zA-Z]+");

In the argument to the useDelimiter method, the brackets specify a group of characters, the ‘∧ ’ specifies
the complement of the characters that follow, and ‘+’ is shorthand for any positive number of occurrences
0.3 Arrays 17

of the preceding group. In other words, we are defining a delimiter as any sequence of one or more
occurrences of characters that are non-alphabetic. So if we have included the above useDelimiter call,
and we have
split ("Here today, gone tomorrow.");

then the output will be

here
today
gone
tomorrow

Finally, suppose we want to allow a word to have an apostrophe. Then we include the apostrophe in the
class whose complement defines the delimiters:
Scanner sc = new Scanner (line).useDelimiter ("[∧ a-zA-Z’]+");

If the call is
split ("You’re 21?? I’ll need to see some ID!");

then the output will be

you’re
i’ll
need
to
see
some
id

You are now prepared to do Lab 0: The Scanner Class

Cultural Note: The Scanner class enables a user to process a regular expression: a format for identifying
patterns in a text. The arguments to the useDelimiter methods shown previously are simple examples
of regular expressions. In general, regular expressions provide a powerful but somewhat complex means
of finding strings of interest in a text. For more information on handling regular expressions in Java, see
http://www.txt2re.com and (Habibi, 2004).

0.3 Arrays
An array is a collection of elements, of the same type, that are stored contiguously in memory. Contiguous
means “adjacent,” so the individual elements are stored next to each other.3 For example, we can create
an array of five String objects as follows:
String [ ] names = new String [5];

3 Actually, all that matters is that, to a user of an array, the elements are stored as if they were contiguous.
18 C H A P T E R 0 Introduction to Java

Here the new operator allocates space for an array of five String references (each initialized to null by
the Java Virtual Machine), and returns a reference to the beginning of the space allocated. This reference
is stored in names.
In order to specify one of the individual elements in an array, an index is used. An index is an
integer expression in square brackets; the value of the expression determines which individual element is
being denoted. The smallest allowable index is 0. For example,
names [0] = "Cromer";

will store a reference to “Cromer” at the zeroth entry in the array (referenced by) names.
The size of an array is fixed once the array has been created, but the size need not be determined at
compile-time. For example, we can do the following:
public void processInput (String s)
{
int n = new Scanner (s).nextInt();

String [ ] names = new String [n];


...

When the processInput method is executed at run time, names will be assigned a reference to an array
of n string references, all of which are initialized to null. An array is an object, even though there is
no corresponding class. We loosely refer to names as an “array,” even though “array reference” is the
accurate term.
The capacity of an array, that is, the maximum number of elements that can be stored in the array,
is stored in the array’s length field. For example, suppose we initialize an array when we create it:
double [ ] weights = {107.3, 112.1, 114.4, 119.0, 117.4};

We can print out the capacity of this array as follows:


System.out.println (weights.length);

The output will be

For an array x, the value of any array index must be between 0 and x.length-1, inclusive. If the value
of an index is outside that range, ArrayIndexOutOfBoundsException (See Section 2.3 of Chapter 2
for a discussion of exception handling) will be thrown, as in the following example:
final int MAX = 10;

double [ ] salaries = new double [MAX];

for (int i = 0; i <= MAX; i++)


salaries [i] = 0.00;

For the first ten iterations of the loop, with i going from 0 through 9, each element in the array is initialized
to 0.00. But when i gets the value 10, an ArrayIndexOutOfBoundsException is thrown because i’s
value is greater than the value of salaries.length-1, which is 9.
0.4 Arguments and Parameters 19

0.4 Arguments and Parameters


In Java, the relationship between arguments (when a method is called) and parameters (in the called
method’s heading) is straightforward: a copy of the value of the argument is assigned to the parameter.
So the argument is not affected by the method call. For example, consider the following program:
public class Nothing
{
public static void main (String[ ] args)
{
new Nothing().run();
} // method main

public void run()


{
int k = 30;

triple (k);

System.out.println (k);
} // method run

public void triple (int n)


{
n = n * 3;
} // method triple

} // class Nothing

The output will be 30. When the method triple (int n) is called, a copy of the value of the argument
k is assigned to the parameter n. So at the beginning of the execution of the call, n has the value 30. At the
end of the execution of the call, n has the value 90, but the argument k still has the value 30. Incidentally,
the name of the parameter has no effect: the result would have been the same if the parameter had been
named k instead of n.
Next, we look at what happens if the argument is of type reference. As with primitive arguments,
a reference argument will not be affected by the method call. But a much more important issue is “What
about the object referenced by the argument?” If the object is an array, then the array can be affected by
the method call. For example, here is a simple program in which an array is modified during a method
call:
public class Swap
{
public static void main (String[ ] args)
{
new Swap().run();
} // method main

public void run()


{
20 C H A P T E R 0 Introduction to Java

double[ ] x = {5.0, 8.0, 12.2, 20.0};

swap (x, 1, 2);

System.out.println (x [1] + " " + x [2]);


} // method run

public void swap (double[ ] a, int i, int j)


{
double temp = a [i];
a [i] = a [j];
a [j] = temp;
} // method swap

} // class Swap

The output will be

12.2 8.0

In the array referenced by x, the elements at indexes 1 and 2 have been swapped.
For objects other than arrays, whether the object can be affected by the method call depends on the
class of which the object is an instance. For example, the String class is immutable, that is, there are
no methods in the String class that can modify an already constructed String object. So if a String
reference is passed as an argument in a method call, the String object will not be affected by the call.
The following program illustrates the immutability of String objects.
public class Immutable
{
public static void main (String[ ] args)
{
new Immutable().run();
} // method main

public void run()


{
String s = "yes";
flip (s);
System.out.println (s);
} // method run

public void flip (String t)


{
t = new String ("no");
} // method flip
} // class Immutable

The output will be “yes”. The flip method constructed a new String object, but did not affect the
original String object referenced by s. Figure 0.3 shows the relationship between the argument s and the
parameter t at the start of the execution of the call to the flip method. Figure 0.4 shows the relationship
between s and t at the end of the execution of the method call.
0.4 Arguments and Parameters 21

s
yes

FIGURE 0.3 The relationship between the argument s and the parameter t at the start of the execution of the
flip method in the class Immutable

s
yes

t
no

FIGURE 0.4 The relationship between the argument s and the parameter t at the end of the execution of the
flip method in the class Immutable

Some built-in classes are mutable. For example, the following program illustrates the mutability of Scanner
objects.
import java.util.*; // for the Scanner class

public class Mutable


{
public static void main (String[ ] args)
{
new Mutable().run();
} // method main

public void run()


{
Scanner sc = new Scanner ("yes no maybe");

System.out.println (sc.next());
advance (sc);
System.out.println (sc.next());
} // method run

public void advance (Scanner scanner)


{
scanner.next();
} // method advance

} // class Mutable

The output from this program will be


yes
maybe
22 C H A P T E R 0 Introduction to Java

The string “no” was returned when scanner.next() was called in the advance method, and that call
advanced the current position of the Scanner object (referenced by both sc and scanner) beyond where
“no” is. Because of this alteration of the Scanner object, the second call to println in the run method
prints out “maybe”.
To summarize this section, an argument is never affected by a method call. But if the argument is a
reference, the corresponding object may (for example, an array object or a Scanner object) or may not
(for example, a String, Integer, or Double object) be affected by the call.

0.5 Output Formatting


What do you think the output will be from the following code fragment?
double grossPay = 800.40;

System.out.println (grossPay);

The output will not be


800.40
but rather
800.4
To get two fractional digits printed, we need to convert grossPay to a string with two fractional digits. This
is accomplished by first creating an instance of the DecimalFormat class (in the package java.text)
with a fixed format that includes two fractional digits, and then applying that object’s format method to
grossPay. The code is
DecimalFormat d = new DecimalFormat ("0.00");

double grossPay = 800.40;

System.out.println (d.format (grossPay));

The fixed format, “0.00”, is the argument to the DecimalFormat constructor. That format specifies that
the String object returned by the format method will have at least one digit to the left of the decimal
point and exactly two digits to the right of the decimal point. The fractional part will be rounded to two
decimal digits; for example, suppose we have
DecimalFormat d = new DecimalFormat ("0.00");

double grossPay = 800.416;

System.out.println (d.format (grossPay));

Then the output will be


800.42
To make the output look more like a dollar-and-cents amount, we can ensure that grossPay is immediately
preceded by a dollar sign, and a comma separates the hundreds digit from the thousands digit:
DecimalFormat d = new DecimalFormat (" $#,###.00");

double grossPay = 2800.4;

System.out.println (d.format (grossPay));


0.5 Output Formatting 23

The output will be

$2,800.40

The DecimalFormat class is in the package java.text, so that package must be imported at the begin-
ning of the file in which the formatting is performed.
An alternative to the output formatting just described is provided by the printf method, which is
similar to the printf function in the C language. For example, the following will print grossPay with at
least one digit to the left of the decimal point and exactly two digits (rounded) to the right of the decimal
point:
System.out.printf ("%1.2f", grossPay);

The first field is called the format, an expression in quotes that starts with a percent sign. The character
‘f’—called a “flag”—signifies that grossPay will be printed with fractional digits. The “1.2”—the “width”
and “precision”—signifies that there will be at least one digit (even if it is a zero) to the left of the decimal
point, and exactly two digits (rounded) to the right of the decimal point. For example, suppose we have
double grossPay = 1234.567;

System.out.printf ("%1.2f", grossPay);

Then the output will be

1234.57

If there are additional values to be printed, the format for each value starts with a percent sign inside the
format. For example,
double grossPay = 1234.567;

String name = "Jonathan Rowe";

System.out.printf ("%s %1.2f", name, grossPay);

The ‘s’ flag indicates a string. The output will be

Jonathan Rowe 1234.57

We can ensure there will be a comma between the hundreds and thousands digits by including the comma
flag, ‘,’. For example, suppose we have
double grossPay = 1234.567;

String name = "Jonathan Rowe";

System.out.printf ("%s $%,1.2f", name, grossPay);

Then the output will be

Jonathan Rowe $1,234.57

More details on formatting in the printf method can be found in the Format class in the package
java.util.
24 C H A P T E R 0 Introduction to Java

CROSSWORD PUZZLE

5 6

www.CrosswordWeaver.com

ACROSS DOWN

3. A variable that can contain the address of an object. 1. The ability of a class to have methods with
the same method identifier but different
6. The region of a program to which an identifier’s parameter lists.
declaration applies.
2. A method’s identifier together with the
7. The separation of a program into components that number and types of parameters in order.
are coherent units.
4. Adjacent, as when individual elements are
8. A new, that is, non-primitive type. stored next to each other.

9. In a class, a method whose name is the same as the 5. An instance of a class.


class’s name and whose purpose is to initialize a calling
object’s fields. 6. A class that is useful for parsing keyboard
input, file input and strings.
Programming Exercises 25

PROGRAMMING EXERCISES
0.1 The package java.lang includes the Integer class. In that class, what is the definition of MAX_VALUE ? The
number 0x7fffffff is in hexadecimal , that is, base 16, notation. To indicate hexadecimal notation, start with
“0x”, followed by the hexadecimal value. In hexadecimal, there are sixteen digits: 0, 1, 2, . . ., 9, a, b, c, d,
e, and f. The digits 0 through 9 have the same value as in decimal, and the letters ‘a’ through ‘f’ have the
following decimal values:
a 10
b 11
c 12
d 13
e 14
f 15

The decimal representation of hexadecimal 7ffffff is


7 ∗ 167 + 15 ∗ 166 + 15 ∗ 165 + 15 ∗ 164 + 15 ∗ 163 + 15 ∗ 162 + 15 ∗ 161 + 15
= 2147483647
Similarly, the decimal value of MIN_VALUE is −2147483648. Hypothesize the decimal value of each of the
following:

Integer.MAX_VALUE + 1

Math.abs (Integer.MIN_VALUE)

Test your hypotheses with a small program that calls the System.out.println method.
0.2 Suppose we have the following:

int a = 37,
b = 5;

System.out.println (a - a / b * b - a % b);

Hypothesize what the output will be. Test your hypothesis by executing a small program that includes that code.
Can you find another pair of positive int values for a and b that will produce different output? Explain.
0.3 Hypothesize the output from the following:

System.out.println (1 / 0);
System.out.println (1.0 / 0);

Test your hypotheses by executing a small program that includes that code.
0.4 In the String class, read the specification for the indexOf method that takes a String parameter. Then
hypothesize the output from the following

System.out.println ("The snow is now on the ground.".indexOf ("now"));

Test your hypothesis by executing a small program that includes that code.
26 C H A P T E R 0 Introduction to Java

0.5 In the String class, read the specification for the indexOf method that takes a String parameter and an
int parameter. Then hypothesize the output from the following

System.out.println ("The snow is now on the ground.".indexOf ("now", 8));

Test your hypothesis by executing a small program that includes that code.
0.6 Write and run a small program in which an input string is read in and the output is the original string with each
occurrence of the word “is” replaced by “was”. No replacement should be made for an embedded occurrence,
such as in “this” or “isthmus”.
0.7 Write and run a small program in which an input string is read in and the output is the original string with each
occurrence of the word “is” replaced by “is not”. No replacement should be made for an embedded occurrence,
such as in “this” or “isthmus”.
0.8 Write and run a small program in which the end user enters three lines of input. The first line contains a string,
the second line contains a substring to be replaced, and the third line contains the replacement substring. The
output is the string in the first line with each occurrence of the substring in the second line replaced with
the substring in the third line. No replacement should be made for an embedded occurrence, in the first line of
the substring in the second line.
0.9 Study the following method:

public void mystery (int n)


{
System.out.print ("For n = " + n);
while (n > 1)
if (n % 2 == 0)
n = n / 2;
else
n = 3 * n + 1;
System.out.println (", the loop terminated.");
} // method mystery

Trace the execution of this method when n = 7. In the same class as the method mystery, develop a main
method and a run method to show that the while statement in the method mystery successfully terminates
for any positive integer n less than 100. Cultural note: It can be shown that this method terminates for all int
values greater than 0, but it is an open question whether the method terminates for all integer values greater
than 0.
Another random document with
no related content on Scribd:
The Project Gutenberg eBook of The
American historical novel (on American
themes) before 1860
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: The American historical novel (on American themes) before


1860
the early novels of James Fenimore Cooper (1821-1831)

Author: Ernest Erwin Leisy

Release date: May 4, 2024 [eBook #73537]

Language: English

Original publication: Urbana: University of Illinois Press, 1923

Credits: Charlene Taylor and the Online Distributed Proofreading


Team at https://www.pgdp.net (This file was produced
from images generously made available by The Internet
Archive)

*** START OF THE PROJECT GUTENBERG EBOOK THE AMERICAN


HISTORICAL NOVEL (ON AMERICAN THEMES) BEFORE 1860 ***
THE AMERICAN HISTORICAL NOVEL
(ON AMERICAN THEMES)
BEFORE 1860
THE EARLY NOVELS OF
JAMES FENIMORE COOPER
(1821–1831)

BY
ERNEST ERWIN LEISY
A.B., University of Kansas, 1913
A.M., University of Chicago, 1919
AN ABSTRACT OF A THESIS
SUBMITTED IN PARTIAL FULFILLMENT OF THE REQUIREMENTS
FOR THE DEGREE OF DOCTOR OF PHILOSOPHY IN
ENGLISH IN THE GRADUATE SCHOOL OF THE
UNIVERSITY OF ILLINOIS, 1923
URBANA, ILLINOIS
THE EARLY NOVELS OF
JAMES FENIMORE COOPER (1821–1831)
James Fenimore Cooper—so the popular legend runs—was a
man who wrote stories about idealized Indians and the wilderness,
now read mainly by boys; who created Leatherstocking, the man
without a cross; and who spent an irascible old age winning petty
lawsuits. Further reflection may call to mind that he was enamored
of the sea as well as of the wilderness, and that one of his stories
had something to do with a spy. All this, of course, is true; but that
Cooper did much more than this, has been discovered comparatively
recently. The explanation is to be found, in part, in the fact that after
Cooper’s death in 1851, the vogue of his type of romance having
passed also, his popularity suffered a decline reaching its lowest ebb
between 1870 and 1880. Another reason is that the novelist’s dying
injunction that no biography be authorized was carried out so
literally by his oldest daughter and literary executrix that many
family papers of value were destroyed. She afterwards published in
the Atlantic Monthly for 1887 two reminiscent articles about her
father, but these are rambling and uninformative in character. In
1883—thirty years after the death of the novelist—Professor
Lounsbury succeeded surprisingly well in piecing together the
1
outward facts of Cooper’s life. The “Correspondence of Cooper,” just
2
published, reveals little about the workmanship or about the
personality of the novelist, except by way of emphasizing the fact
that his social and political ideas meant more to him than his art.
Cooper’s own introductions, added to his works in 1849, the articles
by his daughter, and the results of Lounsbury must suffice for the
external evidence on Cooper’s work; whatever conclusions are
reached on internal evidence may be modified when materials still in
the possession of the Cooper family are given up to the public.
Of the critical writings concerning Cooper the best is an essay by
W. C. Brownell in American Prose Masters (1909), in which he
applies the canons of criticism to the works of Cooper in toto under
the captions: Form and Substance, Defective Art, Romantic Realism,
Indians, Characters, Women, and Patriotism. John Erskine in Leading
American Novelists (1910), pp. 51–130, has taken up in greater
detail the leading works, using the critical-historical method. Carl
Van Doren in The Cambridge History of American Literature, I, 293–
306, and The American Novel (1921), Chapter 2, follows somewhat
the same method as Erskine. W. L. Cross in The Development of the
English Novel (1899) has a brief but pointed six pages on Cooper
and his relation to Scott and his successors. These critics think highly
of Cooper’s work but have been interested primarily in Cooper’s
results rather than in the history of how Cooper produced his results.
Only Brownell and Erskine incidentally, and Cross briefly, touch upon
Cooper as an historical novelist. Leaving Cooper’s other historical
work out of account, they concentrate upon The Spy, declaring it an
historical novel of adventure, as Cooper had not the background for
genuine historical work and did not test his fictitious characters in
great historical crises such as in Kenilworth or The Abbot. This
seems a too arbitrary restriction of the term “historical,” for which
Brownell makes some amends when he declares that the alliance of
romance with reality in Cooper’s tales, “his general and personal
interest in the life he depicted makes his account of it solider art,
gives his romance even more substance and meaning than Scott’s
3
historiography.” How extensively and well Cooper portrayed the
setting of a past time, how he related his work to his public, what
connection it had with the work of his predecessors and
contemporaries, the consequent originality of his contribution, and
the nature and extent of his influence on the historical novel have
received insufficient attention.
Considering the results of the experiments with native material
outlined in the preceding chapter, Cooper might well have entered
with diffidence upon the task of writing an “American” novel. That he
was in any definite sense aware of the work of his predecessors in
the field of the American novel seems doubtful. His had been a
frontiersman’s boyhood, followed, after an erratic two years at Yale,
by apprenticeship at sea and a decade as a country squire. Then by
the merest chance he fell into authorship. To make good his boast
that he could write a better book than the novel of English society
life which he was at that time reading, he wrote Precaution, a story
of earls and dukes. But knowing how devout an American Cooper
was, some of his friends made it a matter of reproach that he should
have written a novel foreign in substance and feeling. He
acknowledged the justice of the imputation and resolved to atone by
4
inflicting upon the world and himself, as he said, a second book,
The Spy, the patriotic nature of which should admit of no cavil.
From the writing of Precaution, Cooper carried over very little
save ability to manipulate a story. It taught him nothing in the way
of adapting the formula of the current novel to the treatment of
native material. He had still to learn to conform to the principles of
the Waverley novels and at the same time to find a tractable
American theme. What was the nature of the historical novel then
current?
5
“Scott had gathered up,” says Dr. Loshe, “and recombined,
according to formulas of his own, many elements present in the
fiction of his day,—the tendency to localized or national tales with
that interest in humble personages on whom local characteristics are
most deeply impressed, which appears most plainly in Miss
Edgeworth’s Irish stories; the interest in romantic landscape and
word-painting of natural scenery which found its most striking
expression in Mrs. Radcliffe’s theatrical yet impressive scenes; the
tale of adventure reinforced by the revived interest in travel and
antiquarian taste for old buildings and trappings; and the eagerness
for an imaginative interpretation of history which had expressed
itself in many would-be historical tales, whose hopeless inaccuracies
had a naive honesty of good intention.”
These ingredients which Scott had mixed in varying proportions
in his different works, it occurred to Cooper, might be adapted to
native manners and conditions.
The essential requirement of the Scottish novels—conflict,
patriotic association, and difference in social manners—obviously
suggested to Cooper the American Revolution as the scene for his
novel. The details of that warfare, particularly as they were related
by the aged participants in Westchester County, New York, where he
was at this time living, Cooper had listened to with that intelligent
interest with which a seaman may follow strategy on land as well.
He knew this neutral ground, between the British in New York City
and the American army in the highlands of the Hudson, over which
the tide of battle had ebbed and flowed, as Scott knew his native
heath. As he turned over in his mind the possibilities afforded by this
setting he recalled an anecdote which his neighbor John Jay had
related years before concerning a shrewd, unselfishly patriotic spy
employed by him during the war. This “legend” became the nucleus
of his story. Judging from internal evidence, Cooper must have been
delighted with the possibilities of the subject for was it not still a
matter of record how the sensibilities of the public had been
6
wrought upon by the fate of Hale and of Andre? Was not his friend,
Dunlap attracting multitudes to his play, entitled Andre? It next
occurred to him to present his spy in the guise of a pedlar such as
Edie Ochiltree, who had fascinated readers of The Antiquary. So
vividly did Cooper realize his conception of Harvey Birch that the
romance had all the semblance of a memoir.
The public veneration for Washington required that he be
introduced somehow. In 1780 the patriot army, under General
Washington, occupied a line of connecting positions extending from
Philadelphia across northern New Jersey, to the fortified post of West
Point on the Hudson. Along the Hudson River, the American lines
extended to Peekskill, and outposts patrolled the country as far
south as Tarrytown. From this point to the channels which separate
Manhattan Island from the mainland, a distance of about forty miles,
lay the “neutral ground,” the No Man’s Land of the Revolution. It was
the object of the patriot army to prevent the British forces from
drawing supplies from this region, but Congress would not permit
devastation. Consequently, the “neutral ground,” swept by constant
raids, and exposed to the unchecked evils of civil war, became the
abode of the lawless and adventurous spirits who flourish best in
times of upheaval and disorder. The fall of Charleston, the treason of
Arnold, and dissensions among officers of the Continental Army
made a general disintegration of that military force which was the
sole support of the patriot cause seem at hand. The Revolution was
in danger, not only from avowed Tories but from lukewarm followers
anxious to keep on the winning side. This combination of
circumstances suggested to Cooper the military situation in 1780 in
the Neutral Ground as the most suitable background for his story.
Romantic themes were for Cooper more important and
interesting than restoration of the historic past. The instinctive
Toryism that made it natural for Scott to poetize history had no
7
counterpart in Cooper’s rationalized liberalism. But it was not
necessary for his mind to be saturated with history as was that of
Scott. Compared with Europe, America had little history, and that
little Cooper knew, particularly as it pertained to New York. In the
present instance, he had his information from eye-witnesses and
from nine years’ residence on the scenes. It was decidedly to
Cooper’s advantage to have a “legend,” or the outline of a plot,
suggested to him, since, with this in mind, he could in unfolding a
story give to it all the illusion of reality. “Perhaps by chance,” says
Carl Van Doren, “Cooper here hit upon a type of plot at which he
excelled, a struggle between contending forces, not badly matched,
arranged as a pursuit in which the pursued are, as a rule, favored by
8
the author and reader.” High and low characters could easily be
borrowed, in fact, his public expected that. The Wharton family,
consisting of a high-spirited young blond, a faded elder daughter, a
young officer, and a feeble father was the conventional novel family;
the pedlar as the central link of the action came from The Antiquary;
Dr. Sitgreaves was an imitation of Scott’s pedants; Betty Flanagan,
the sutler, partook of the nature of Miss Edgeworth’s Irish characters
of low life; the negro was an adaptation of the court fool; the
remaining characters were be-captained and be-majored as was
fitting in a tale of love and war.
As much of his public was Tory, and as even English readers
might be appealed to, Cooper faced the problem of writing his story
so as to please the patriot and to enlist the interest of these others
besides. Fortunately for Cooper, and for art in American historical
fiction, his training under an Anglican tutor and his marriage into a
Tory family restrained him from such partiality for the Americans as
the first historical novelist might easily have indulged in and thereby
set the standard for succeeding writers. Cooper’s solution in taking a
house divided against itself, in a section supposedly neutral but
actually overrun by skirmishing parties of either side, supplied also
the essential element of conflict. He added suspense by the
uncertainty he created in the reader’s mind as to which party the spy
served and by having him persecuted equally by bands of Skinners
and by Cowboys. With the sketch of the depredations of the
Skinners he enlisted Tory approval of the veracity of the picture. The
first volume was in fact as inviting to loyalist as to patriot. The
mysterious Harper, though he inspired considerable awe, had little in
his reticent demeanor to indicate that he was the commander-in-
chief of the continental troops. But the patriotic purpose of the book
was not to be lost sight of. In his very persecutions the spy was
becoming heroic, and there could be no mistake as to his position in
the outcome. By making the heroine, regardless of her Tory family,
espouse the American cause, and by exposing as a bigamist the
English colonel, with whom her sister was in love, the author further
won the favor of the patriot. Here and there he added touches of
piety which might bring his fable into favor with the reader.
The handling of historical matter, particularly the treatment of
Washington, presented a problem of peculiar difficulty. According to
Scott’s practice up to this time, an historical character must have a
minor role. This should have simplified the problem but Washington
was too much venerated to be simply disposed of. Cooper hit upon
the solution of introducing him as the shadowy Mr. Harper, who
looms somewhat gigantically through his disguise, and is revealed, in
the end, as the ally of the spy and the patriot leader. While Cooper
displayed a gift for historical portraiture, he fell victim to the
contemporary notion of Washington and portrayed him as the
sobered and aged President rather than as the General of the
Continental Army. His stiffness en famille and his melodramatic
skulking about the highlands and in caves were later by Cooper
himself acknowledged a mistake. But to the general historical facts
of his story Cooper was true. Truer, in fact, than the historians. And
this, as has never been pointed out, constitutes The Spy a document
of historical value. For the Whig historians, following the Revolution,
had misrepresented the war as a united uprising against the mother
country instead of the civil conflict, which, according to the best
modern criticism, it in large part was. The intense Whig tradition
begun by Andrews and Gordon, who based the earliest histories of
the Revolution on Burke’s yearly summaries of the events in the
Annual Register, persisted not only in Weem’s Life of Washington but
in Marshall’s also, and was influential through the ten editions of
Botta’s translation. The federalism of Hildreth (1849) carried on this
bias; and when Bancroft in 1852 reached the Revolution, he broke
all records for a violently partisan and timorously defensive history of
9
the Revolution. For leaving a distinct impression of the fratricidal
nature of the strife, when a just version of the struggle seemed
impossible, Cooper deserves credit hitherto not accorded him.
The Spy, as I have tried to indicate, was in every sense an
experiment. If it succeeded, others of its kind might follow; if it
failed, the American novel would have to wait, for Irving, Cooper’s
only possible competitor, “deliberately chose short stories to avoid
10
any rivalry with Scott.” But so well had Cooper estimated the
tastes of the public that the experiment was from the first a success.
In three months it was in its third edition. It won the “respect of the
11
generally contemptuous English critics, and the American press,
which had liked the book by instinct, was pleased with the mild
12
praise as though it were a national tribute.” The happy issue of
the experiment inspirited other native writers; it encouraged Cooper
in particular.
For a novitiate like Cooper to follow up at once the career
unexpectedly opened up to him by the success of The Spy, required
that he draw upon material already in hand. His acquaintance with
Westchester county he had used felicitously; there remained his
boyhood at Cooperstown, and his years at sea. Affection for the
pioneer village among the forest-clad hills surrounding Otsego
pressed for utterance and Cooper began “a descriptive tale” which
he named The Pioneers; or, the Sources of the Susquehanna (1823).
With a few Cooperstown characters and the outlines of a situation in
mind, Cooper launched upon the improvisation of his story. He
13
transcribed and generalized for the purposes of fiction his
memories of the hunter, Shipman, who came to his father’s, Judge
Cooper’s, Hall to present his game; the motley characters and
nationalities of the early settlement; the town itself as it was forty
years ago, with its raw street of wooden houses; the drunken Indian
at the inn; the snowy congregation crowding to the fire at the
church; the seasonal sports of the rough people; the virgin lake and
wilderness, the forest conflagration, ushering out with grim reality
the period of romance. Cooper was too downright to obscure the
grossness of the picture. Derelicts and scoundrels he well knew were
associated with a new society as much as its idealists, and he
brought them in. Representatives of various social units were made
to aid in the evolution of the plot. Judge Temple, empire-builder,
with his daughter just home from school, and an insurgent young
Effingham were given the center of the stage; Natty Bumppo,
protagonist of the advancing civilization, his companion
Chingachgook, christened John, and various frontier types, were
grouped about these.
In this work, Cooper showed a more aggressively American
spirit, derived no doubt from the favorable reception accorded The
Spy. In both the subject-matter and in his presentation of it he was
independent of Scott,—seeking in the picture of American empire-
building and American prodigality to set his country honorably before
foreign readers. As was fitting in an avowedly “descriptive tale,” he
laid aside the “pursuit-rescue” scheme for a set of sportsman’s
sketches not unreminiscent of Irving. Life in the American
14
Bracebridge Hall was exhibited, with its Christmas abundance not
to be outdone by Irving’s sketch of an English Christmas, and its
sports like the turkey-match, the shooting of myriads of wild-
pigeons, the seining or spearing of bass, the deer-chase on the lake,
maple-sugaring in spring, and sleighing-parties in winter, each
carrying its peculiar appeal. But there was also dramatic tension and
an interest in a theme suggesting Greek fatalism: the law of nature,
embodied in the uncouth old hunter and the Great Serpent, is seen
in conflict with the law of man represented by the Judge. In the end
the law of nature yields to the stocks and the fire which civilization
brought, and the only escape is a reluctant departure toward the
setting sun. A conventional plot was introduced by Cooper as a
concession to his readers, but it is of secondary importance. A wrong
done by Judge Temple to Effingham’s father is righted by the slightly
complicated love-match of Miss Temple with young Effingham, in
fiction a favorite method of restitution. The girl’s excessive
sensibility, the episode of the panther, the appearance of a sybil, and
of a gold-digger, the hero’s clouded ancestry cleared up in the
penultimate chapter, all are to us dregs in the old wine but gave the
story the flavor it needed in order to sell; the new wine that Cooper
introduced has ripened to modern taste: it is the “essential wonder
of pioneer life” as it is presented in this epic of the wilderness.
The Pioneers has never received consideration as an historical
15
novel. Van Doren speaks of it as Cooper’s first “realistic
presentation of American manners.” Yet a novel of manners it is not.
That life in the frontier town was not what it had been and never
16
would be again, Cooper realized definitely. Susan Fenimore Cooper
17
says, “The new narrative, like that which preceded it, was, in one
sense, to be connected with the history of the country; it should
follow the first steps of civilization in its conquests over the
wilderness.” The conceivable contention that more than forty years
must elapse between the time of the action and the date of
composition is invalid: forty years is exactly the length of time by
which The Spy, generally acknowledged an historical novel, is
separated from its events; and The Antiquary is remote only twenty-
one years. In America, moreover, changes in manner, customs and
outward appearances are so great in a single generation that the
18
historical romancer need not revert to antiquity. It might, further,
be argued that no actual historical character appears in the book.
But the contemporary imagination did not heed to be reminded that
here was the story of Daniel Boone, for to it the story had become a
19
legend. There is abundant evidence that its readers regarded it as
an historical novel. So well did Cooper understand the passing
nature of this pioneer life and so effectively did he characterize it
here, that with subsequent writers the novel of pioneer community
20
life became the characteristic type of American historical novel.
In The Pilot (1823) Cooper drew upon his experiences at sea.
How thoroughly he was at home here his biographers have
remarked, but how thoroughly he viewed life from a seaman’s point
21
of view, they have not insisted upon. When it was apparent that
Yale would do him no good, Cooper’s father shipped him before the
mast, and here on his first voyage, which was long and stormy,
occurred an unforgettable chase by pirates and a search by a British
man-of-war. Such adventures were ordinarily discussed over a cob-
pipe, on a wharf-barrel, or, at most, got into chap books, but no one
thought to put them into a novel, for who but landsmen read
novels? Smollett, to be sure, had had sailors but the detailed
maneuvers of vessels and the tang of the old salt he had not given.
Nor was it done, to Cooper’s thinking, in The Pirate, which had just
appeared anonymously. When he asserted that it was the work of a
landsman and not a of sailor, he was challenged to make good his
contention by writing a story from the seaman’s point of view. His
pugnacious temper was as ready to take the dare as it had been
when it first tripped him into the authorship of Precaution.
Not unmindful of the experimental character of the venture, and
wise through the unexpected success of The Spy, Cooper
determined to blend nautical fiction and history. “It was conceived
22
necessary,” says his daughter, “to connect with the narrative some
historical name which should give it importance, and for the same
reason, the period of the Revolution was chosen as the date of the
tale. The nautical annals of that time were brief, and a rapid glance
was sufficient to show that among the historical figures that of the
bold adventurer, Paul Jones, stood prominent as one of the few
adapted to a work of fiction. His cruise in The Ranger suggested the
plot of The Pilot.”
The historical facts in brief were these. Jones, after receiving a
lieutenant’s commission in the navy, suggested that the American
vessels, which were few and inferior in comparison with those of the
enemy, should be used as privateers. In the “Ranger” he captured
several trading vessels in the Irish channel; he attacked his home
town of Whitehaven on the coast of Cumberland, and burned one
vessel; he sacked Lord Selkirk’s castle, and defeated and captured
the “Drake,” an English sloop-of-war, with the loss of only eight men.
Cooper chose the northeastern coast of England as the setting
for his story. This gave him the two-fold advantage of exploiting sea
maneuvers which The Pirate lacked, and of complicating these with
a love story in the castle, which readers of Abbey romances
cherished. In their eagerness to point out its novelty as a sea tale,
students of Cooper have overlooked the Gothic tradition which The
Pilot continued. In the management of the story there was not so
much that was new as might be supposed, for in its general outlines
it was The Spy done in terms of the sea. The skirmishes of the
Neutral Ground became chases between frigates and men of war,
the devotion of Harvey Birch was supplanted by Long Tom Coffin’s
love for the sea, and an incognito Paul Jones replaced an incognito
Washington. But such economy of creative effort was justifiable and
perhaps necessary for Cooper if he should lavish upon the details the
interpretative sympathy that he was fitted to give. It was the sailor
in him that led the frigate through the channel in masterful manner
and that made his seamen such likeable fellows. He knew how good
sea-dogs would itch for a fight or boast of their prowess. “Their
ships were handled,” says Captain Mahan, “as ships then were and
23
act as ships still would under the circumstances.” Joseph Conrad
24
has been glad to acknowledge that Cooper taught him profound
sympathy and artistic insight into the sublimity and mystery of the
sea.
Cooper’s choice of the “Father of the American Navy” as the
historical figure with which to connect his sea tale was peculiarly
happy in view of public enthusiasm following the success of the navy
25
in the War of 1812. But in portraying this character he has been
considered no more successful than he had been with Washington.
The statuesque pose of Mr. Gray becomes, through reiteration, an
affectation which it is hard to reconcile with the fiery Scotchman of
history. Cooper himself at a later date expressed dissatisfaction with
26
the unreality of the portrait. It becomes clear in the course of this
story that Cooper regards Paul Jones as a free-lance whose devotion
to America proceeded from his desire of personal distinction. “A
large part of his behavior might be called Byronic,” Erskine has
suggested, “since it appears to be learned in the general school of
27
the Giaour and the Corsair.” As an historical document The Pilot
has worth because it faithfully portrays the sea life of the time of the
Revolution and because it has called attention to a phase of the war
historians have been inclined to neglect.
The favor with which Cooper’s three historical novels had been
received convinced him that here lay his field. How seriously Cooper
considered himself an historical novelist and how auspicious were
the times for a national romancer has not been understood. The
fiftieth anniversary of the battles of Lexington, Concord, and Bunker
Hill was at hand. The spirit of nationalism was intense. President
Monroe had promulgated his Doctrine, General LaFayette (a personal
friend of Cooper’s) had come to tour the country he had helped to
save, and Daniel Webster in his Bunker Hill oration was trying to put
into pleasing phrase the popular mood. Cooper, in the blush of
popularity, conceived a plan for a series of historical romances, on a
national scale, to be called “Legends of the Thirteen Republics,” the
scenes of which should be laid in the various colonies that had
shared in the Revolution. The first of this series was devoted to
Massachusetts, and was entitled, Lionel Lincoln, or the Leaguer of
28
Boston (1825).
29
“Nothing that industry could do,” says Lounsbury, “was spared
by Cooper to make this work a success. In the preparation of it he
studied historical authorities, he read state papers, he pored over
official documents of all kinds and degrees of dreariness. To have his
slightest assertions in accordance with facts, he examined almanacs,
and searched for all the contemporary reports as to the condition of
the weather. He visited Boston in order to go over in person the
ground he was to make the scene of his story.” He built his story
around the battles of Lexington, Concord, and Bunker Hill. The
entrance of a vessel through the patrolled part of Boston, carrying
young Lincoln, an officer in the British service; the journey past old
North Church, the Province House, and Faneuil Hall to the heart of
the city; the state of unrest among the citizenry, along with the
doubt among the British whether the rabble will fight; the
organization of the Sons of Liberty and the news of the coming of
Clinton, Burgoyne, and Howe; a spirited account of the running fight
from Lexington to Concord; the uprising of a hundred thousand men
under leaders like Warren, Putnam, and Gage; and at length an
account of the Battle of Bunker Hill, in which the hero is wounded,
were put into the first volume. In the second, history was practically
cast to the winds, and the private fortunes of the hero were related,
—his recovery under the tender ministrations of a girl, his marriage
to her, amid ominous portents, and the disclosure through the
spectacular machinery of Gothic romance of what had been clouded
regarding his ancestry.
For the first time in his treatment of American history, Cooper
had a subject in which he was obliged to substitute for personal
experience painstaking research. Not having been very successful in
handling character that required adherence to historical fact, it was a
question whether his mind could assimilate the results of his
investigations in a way to stimulate rather than to hamper his
imagination. For better or for worse, he made no attempt to
delineate an historical character. Warren, Gage, and Putnam he
mentioned but their possibilities as literary material he did not
recognize; Burgoyne, Howe, and Clinton he misrepresented in the
few pages he allotted to them. With the historical background in and
about Boston he was more successful, giving according to Bancroft,
an effective and truthful rendering. As heretofore, his sympathy with
the losing side equalized the contest and made it a worthy struggle.
For the critical reader none of his books has a more inviting opening.
But Cooper soon found the attempt to blend his complicated plot of
domestic intrigue with history irksome, and shifted attention to the
melodramatic fortunes of his hero. It is difficult to understand why
he should have made an unheroic English Major the hero of an
American story. It can hardly be explained on the ground of Cooper’s
established antipathy to the New England character, although the
fact that he was too little at home in Massachusetts may have
caused him to piece out the story by giving it a melodramatic turn in
keeping with what was popular on the stage of the day. Mr. Van
30
Doren’s remark that the book “failed to please as his earlier novels
had done” must be accepted with qualification, as contemporary
reviews vouch for its own popularity as well as for that of The
31
Leaguer of Boston, a play based upon it. It would seem that the
“Gothicism” of the story as manifested in the character of Ralph with
his sudden and apparently unaccountable appearances and his
almost supernatural power over the Byronic Lionel, the spectacular
apparition of an overshadowing arm on the wall of King’s Chapel
during the marriage ceremony, and the sudden death of the
simpleton at the hands of his maniac father who dies with him, was
an element in the historical novel that gave it a contemporary appeal
which has been lost in an age of other critical standards.
When Cooper abandoned after the first attempt his cycle of
thirteen romances of the Revolution, he did not give up his career in
the field of historical fiction. In his next work, The Last of the
Mohicans, a Narrative of 1757 (1826), he went back even farther
into his country’s past. In The Pioneers he had sharpened his tools
at frontier material and he now wished to execute a design in which
Indian life should be presented in detail. But comparatively little was
known about the red man at the time. Before the Revolution he had
inspired terror but more recently his melancholy fate was to a
greater or less degree upon the white man’s conscience.
Chateaubriand had given currency to the tradition of the noble
savage, but only an ethnologist like Gallatin or Duponceau had
inquired into his origin, language, religion, ethics, government,
habits and manners, with a sense of their scientific value. Cooper’s
own knowledge of the race was limited to an occasional meeting
with an Indian at Otsego Hall, or a delegation at New York or
Washington. This personal acquaintance he now supplemented,
according to his daughter, by a study of Heckewelder, Colden, Penn,
32
and Smith.
The setting of his story came to Cooper while in 1824 with a
party of English friends he was on a visit to the Lake Champlain
region. At Glenn Falls one of the party directed his attention to the
caverns in the river as a suitable location for a romance. The
suggestion pleased the novelist, and when the ruins of Fort William
Henry nearby came to mind, it occurred to him to use the episode of
the siege and massacre at the fort during the French and Indian War
as the basis of the story. For the adventures of his fictitious
characters with which Cooper came more and more to occupy the
second volume of his novels, he here fell back upon his “pursuit-
rescue” scheme. He managed this scheme with sufficient adroitness
to display, incidentally, a great variety of Indian customs and
traditions.
It is not generally known that Cooper’s Indian was drawn in
33
large part from Heckewelder. This venerable man had been a
Moravian missionary among the Delawares and published some
years later an account which rather idealized them. In view of this
fact, Cooper deserves credit for representing the Indian as cunning
and treacherous as well as generous. When it was objected that he
gave a more favorable picture of the red man than he deserved,
Cooper said:
“It is the privilege of all writers of fiction, more particularly when
their works aspire to the elevation of romances, to present the beau-
ideal of their characters to the reader. This it is which constitutes
poetry and to suppose that the red-man is to be represented only in
the squalid misery or in the degraded moral state that certainly more
or less belongs to his condition, is, we apprehend, taking a very
narrow view of an author’s privileges. Such criticism would have
34
deprived the world of even Homer.”
What Cooper noted about the red men was their acute senses,
developed through woodcraft and warfare, their belief in omens and
their tortoise and beaver worship, their mummery, their stoiclism,
especially when enduring torture at the stake, their “gift” of revenge,
their war dance, their love of baubles, their respect for the feeble-
minded or the aged, their chaste attitude toward female captives,
the silence of the young, their funeral customs and deference to the
mound for the dead, their councils of war and fierce tribal pride,
their use of metaphorical speech, and the crafty eloquence of their
orators.
In order to show the antitheses in Indian character, Cooper
created in Uncas a noble savage, in conformity with the philosophy
of nature then in vogue, and bestowed upon Magua the deceit and
treachery associated with the Indian when he was a menace. With
35
his customary repetition of types, Cooper was inclined to
reintroduce the hunter and his Indian comrade from The Pioneers.
But they were old there and had fallen upon evil days. Yet he
resolved to take the risk. It was a stroke of genius not only to set
them back nearly forty years, but to shown them in the vigor of
manhood undeniably the same individuals. The other characters—an
old man with his motherless two daughters, one of whom is given in
marriage to a representative of the British army for his devoted
services to the family and the other, a quadroon, whose kidnapping
by the Indian villain motivates the pursuit of the second volume—
were redolent of the make-up box and the property-room. The bore,
however, represents a variation from type, as Cooper intended the
half-witted Connecticut psalm-singer for a modern adaptation of the
36
ministrel of medieval romance. The character whose possibilities
Cooper now first realized and upon whom he lavished his devotion
was Natty Bumppo. Upon his Christian stock he grafted many of the
virtues of savage life. It seems to me as if, without consciously doing
so, he has blended in him reminiscences of Sir Charles Grandison
and the natural man of Chateaubriand. In him the historical novel
gained a new type of hero with whose simplicity, downrightness,
competence, unsophistication, and virgin prejudice the natural
37
American has for Europeans come to be identified. How
indigenous he was appears when he is compared with Rip Van
Winkle and the characters of Irving. Thackeray declared La Longue
Carabine one of the great prizemen of fiction. “He ranks,” said he,
“with your Uncle Toby, Sir Roger de Coverley, Falstaff ... and the
38
artist has deserved well of his country who devised them.”
The historical element centering about the siege of Fort William
Henry and the subsequent massacre, Cooper might have gotten up
in an hour’s reading. Perhaps its scant basis of fact accounts for the
truth of the picture. Colonel Munro, the English commander, was
“elaborated according to the needs of the plot and Cooper’s idea of
the British soldier of the period,” says Erskine. “As a soldier he is of
course brave, but not astute. Cooper lets him stand for the usual
British incapacity to cope with the Indians which Braddock so fatally
39
illustrated.” It is not likely that any of Cooper’s readers would have
impugned the conception. The portrait of Montcalm is, in my
40
judgment, Cooper’s best picture of an historical character. Deeply
regretting that history would perpetuate only his glorious death on
41
the Plains of Abraham, Cooper without pronouncing final
judgment upon his conduct, represented Montcalm as putting policy
above moral principle when he did not, by restraining his Indian
allies, prevent the massacre which followed the capitulation of the
42
English. In this position he was in accord with Timothy Dwight, a
careful historian, who remembered the event as a child and
expressed the view which prevailed in New England and New York.
The massacre itself, with its opportunity for pageantry in Scott’s
vein, did not fire Cooper’s imagination.
What Cooper did in The Last of the Mohicans that he had not
done so well in his previous historical novels, was to make the
central theme, the conquest of the Indian by the white, turn upon
and be explained by the chief historical event of the book, the
savagery of the red men at Fort William Henry. He achieved a skillful
blend of research and fabrication that has resulted in its being
regarded the best treatment of the ominous theme of race conflict.
Whatever case the critics may have made against his Indians, and of
late they have rather deferred to him, his conception of the red man
has been effective and is not likely now to be replaced. When people
wish to know what it was to live in the days when the aborigines
were in power, it is to this story of disastrous chances, of hair-
breadth ’scapes, and moving accidents by flood and field, that the
imagination naturally turns.
So well was The Last of the Mohicans received at home and
abroad that Cooper was moved to write at once another tale of the
Indians. The character of Leatherstocking had grown upon him and
he was ready to hazard a third venture with him. The popular mind
had followed the removal of his prototype, Daniel Boone, to the
plains beyond the Mississippi and the report of his recent death
there. In that mysterious Louisiana Purchase, moreover, new
pioneers were seeking to satisfy their hunger for land. Cooper also
knew, though this has not been pointed out before, that the public
mind was further directed to this frontier by the proposal by act of
Congress to remove the Indians to this territory. These
considerations caused Cooper, although he had never seen the
plains, to determine upon a western setting for his next story, The
Prairie (1827).
“During the spring of 1826 Cooper followed a deputation of
Pawnee and Sioux from New York to Washington to study their
43
origin for The Prairie.” The sources which he drew upon Cooper
never indicated directly but it may be pretty safely inferred that he
looked into the Journals of Lewis and Clarke, that he used Long, and
44
perhaps saw Mackenzie. From these he learned of the wild horses,
the buffalo herds, the prairie dogs, flocks of migratory birds, prairie
fires, and mounted Pawnee, Tetons, Konzas, Omahas, and Osages
that were to be found on these endless plains. Among these he
placed a squatter from Kentucky, treking with his family and brother-
45
in-law by prairie schooner across the Nebraska prairie. As Cooper
knew nothing of the life at first hand he was obliged to draw upon
his imagination more largely than heretofore. This he did as easily in
Paris where he was at the time residing as he might have done at
home in New York. As usual he reintroduced many of his characters
from his preceding work. Hawkeye reappeared as the aged trapper,
46
given somewhat more to moralizing. Mahtoree was a slightly
milder Magua mounted on horseback. The Pawnee Hard Heart was
another Uncas, and the psalmist became a pedant in search of
genus and species. The lovers were already married and were kept
in the background. The “pursuit-rescue” device to advance the plot
was continued but was employed with less vigor. In every way the
tone of the story is a more subdued one. Only an assault by Indians,
a stampede by buffalo, the prairie fire, and the consternation over
the treachery of the brother-in-law disturb the author’s brooding
over the epic-vastness of the plains.
Whatever Cooper may have owed to Scott at the beginning of
his career, he owed little to him now. His poetical rendering of the
prairie landscape with its elemental figures was a far cry from the
landscapes of Scott in the style of Mrs. Radcliffe and from his
treatment of characters. Perhaps the greatest change of all was in
Cooper’s central figure, the squatter. Instead of making him heroic,
Cooper showed him untroubled by vision, restless to shake off the
restraints of law and society. His wife, “a shabby, inarticulate prairie
Hecuba,” was Cooper’s first attempt to depict the wife or mother,
and has remained, with Ruth in The Wept of Wish-ton-Wish, his
most noteworthy portrait of a woman. Although Cooper’s story went
back but twenty-three years, its manners were those of a time and
condition remote from his own. Constructed as it was from historical
sources it has further qualification for inclusion here. Its poetic
rendering of the atmosphere of that time and place has given an
effective if not accurate idea of the prairie, an idea which Easterners
have until recently retained.
Cooper’s next novel, The Red Rover (1828), was perhaps his
best sea tale but it was not historical, all details having been
invented “without looking for the smallest aid from traditions or
facts.” Hard upon it came another Indian tale, The Wept of Wish-
ton-Wish (1829). In this novel Cooper turned aside from his
Leatherstocking series, for such his Indian tales had come to be, to
the red man’s last stand against his white opponent in New England
47
in the seventeenth century. Some of his imitators, Miss Child, Mrs.
Cheney, and Miss Sedgwick, had directed attention to early New
England life, and Cooper now turned in the same direction, selecting
the period of King Philip’s war as the basis for his novel of Puritan
life. The account of Eunice Williams’s Indian captivity at Deerfield
had become classic, and Increase Mather and Hubbard had each
given his narrative of the Indian war with the bias of those who
knew the “heathen” chiefly as an enemy. Irving’s short tale, Philip of
Pokanoket (1814) had served as a corrective to this legend. The
episode of Goffe, the regicide, had been treated by Stiles in his
History of the Judges. In fiction, James McHenry, one of Cooper’s
earliest imitators, had dealt with Goffe in a Gothic romance, The
Spectre of the Forest (1823). Scott in his Peveril of the Peak (1823),
48
had called attention to it. As a national romancer, Cooper
doubtless felt it incumbent upon him to make yet another excursion
into New England material.
In the arrangement of his story, Cooper reversed his usual plan,
by making the first half almost wholly fictitious, and putting into the
last half the historical material concerning Goffe, and the
extermination of Philip’s Indian cohorts. The leading episode of the
first volume, an Indian assault upon a settler’s block-house, was
probably suggested by the analogous attack on the feudal castle in
Ivanhoe. Cooper found it difficult to supply a central character as the
Puritans were to him uncongenial. In Captain Heathcote he created
a man of piety, forced to the Connecticut frontier by disagreeable
and petty religious squabbles. The story deals with his domestic life,
his constant fear of attack, and the final assault of Indians who
destroyed his home and kidnapped his daughter. It also treats of a
general renewal of hostilities after an interval of several years during
which American enterprize built up the village of Hartford; of the
timely warning by the mysterious stranger, resulting in the overthrow
of Philip; and of the restitution of the wept-for daughter who clings
to her Indian mate. For the historical background Cooper selected,
49
probably from Trumbull, a few items regarding the early
settlement of Hartford in 1635, which he used for the openings of
his volumes; and then, omitting the early years of the war as
unsuited to his purpose, selected for the dramatic climax the final
hounding and defeat of Canonchet in 1675. A mysterious stranger,
introduced as Submission, is employed in the dénouement to warn
the villagers of the final assault in which he meets his death. The
reader of The Spy and The Pilot, already acquainted with Cooper’s
method of introducing historical characters, had no difficulty in
recognizing Goffe, the regicide.
As an historical novel, The Wept of Wish-ton-Wish was a failure.
Cooper was too much a victim of his early bigoted training to enter
with sympathy into the life of the Puritans. Their religious fanaticism
combined with worldly discretion in exploiting the natives he
illustrated repeatedly. The head and front of their offending he
attributed to their hypocritical pastor, the Reverend Meek Wolfe, who
may or may not have been intended as a caricature of Cotton
Mather. On this incapacity of Cooper’s to depict the founders of New
England, Professor Lounsbury has said: “Paradoxical as the assertion
50
may seem, he was too much like the Puritans to do them justice;”
51
which Professor Erskine has wisely corrected by adding, “In so far
as Puritanism coincided with his nature, he portrayed it admirably in
this novel; he lets the reader see the practical vigor, the exalted
piety, and the domestic affection of Mark Heathcote and his
comrades, for these virtues he can recognize, as he could recognize
the common piety and the common sense of The Pilgrim’s Progress.
But the mastering vision that burns like flame in the Puritan temper,
impelling it to strenuous action, was entirely hidden to Cooper, if we
can judge by his writings....” What further contributed to its failure,
and is not so apparent unless approached from the standpoint of the
historical novel is Cooper’s infelicity in dealing with manners so
remote in time. What people wore, apart from broadswords, he
failed to mention. His Wampanoags were fundamentally not different
from the Hurons he presented in The Last of the Mohicans. As in no
previous book he frequently lapsed into a strained circumlocutory
style that appears to have been meant for the picturesque language
52
of old romance. The braggadocio with which the second volume,
written in Paris, opened, together with the ill-temper displayed
toward the Puritan type, was to bring Cooper into disfavor at home
and abroad. As the next decade of his work was controversial, or
upon European subjects, this chapter may well come to a close here,
deferring the discussion of Cooper’s later, regional novels until some
other time.
In the decade from 1821 to 1831—his most fruitful period—
Cooper was more consistently an historical novelist than has been
recognized. In The Spy he represented more fairly than
contemporary historians the actual nature of the Revolutionary
conflict. The Pioneers immortalized the passing of the frontier, while
The Pilot was our first historical novel of the sea. Lionel Lincoln was
an earnest of national romance, to which he returned in The Wept of
Wish-ton-Wish. In The Last of the Mohicans he set down memorably
the passing of the first American. America was his theme, nothing
more, nothing less. For this task he lacked the historical acumen of
Scott. Of American history in general and of New York history, in
particular, he had a tolerable understanding. His life had fortunately
been sufficiently varied and representative not to necessitate getting
up his local coloring with infinite toil. In one or two cases—so rapid
were social changes—he could depend on aged eye-witnesses for a
reasonably accurate idea of a former day.
His American predecessors taught him practically nothing. From
Scott he learned the general formula for his work. Like him he
turned to native scene as the groundwork for his romance. From
him, also, he learned to give larger place to romantic theme than to
restoration of the past. From him he borrowed the ultraromantic
hero and most of the conventional types of character that he
repeated with little variation in successive novels.
But all this was at the beginning. Once started he was less
influenced by foreign authors and subjects than any of his
contemporaries. In his first book he substituted for lairds, a pedlar,
and in place of a castle he used the Wharton farm-house. Save for
his delineation of certain types, his second book was completely
indigenous. In his third, he outdid the Scotchman himself in giving
the very life of the sea. The Gothic tradition which ran through much
of Scott, Cooper retained only in Lionel Lincoln, finding a more
rational substitute in the terror inspired by the Indians; and, in the
mystery of the sea and the wilderness, a new source of awe.
Because he was not steeped in history and because America’s brief
existence did not make it necessary to delve into antiquity, he
substituted adventure for archaism. He showed that “ivied walls,
time-worn castles and gloomy dungeons, were not necessary to
make a land of romance; that the war of the revolution rivalled, in
romantic interest, the war of the crusaders; that the Indian warrior
equally with the turbaned Saracen, was the theme of the romancer;

You might also like