100% found this document useful (2 votes)
54 views

Building Java Programs: A Back to Basics Approach 4th Edition Stuart Reges - eBook PDF download

The document is an overview of the fourth edition of 'Building Java Programs: A Back to Basics Approach' by Stuart Reges and Marty Stepp, designed for introductory computer science courses. It emphasizes a layered approach to teaching programming fundamentals before introducing object-oriented concepts, along with updates such as a chapter on functional programming and expanded exercises. The textbook aims to improve student success in programming through gradual learning and problem-solving focus.

Uploaded by

divyamoser0v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
54 views

Building Java Programs: A Back to Basics Approach 4th Edition Stuart Reges - eBook PDF download

The document is an overview of the fourth edition of 'Building Java Programs: A Back to Basics Approach' by Stuart Reges and Marty Stepp, designed for introductory computer science courses. It emphasizes a layered approach to teaching programming fundamentals before introducing object-oriented concepts, along with updates such as a chapter on functional programming and expanded exercises. The textbook aims to improve student success in programming through gradual learning and problem-solving focus.

Uploaded by

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

Building Java Programs: A Back to Basics

Approach 4th Edition Stuart Reges - eBook PDF


download

https://ebookluna.com/download/building-java-programs-a-back-to-
basics-approach-ebook-pdf/

Download full version ebook from https://ebookluna.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookluna.com
to discover even more!

(eBook PDF) Building Java Programs: A Back to Basics Approach 4th Edition
by Stuart Reges

https://ebookluna.com/product/ebook-pdf-building-java-programs-a-back-to-
basics-approach-4th-edition-by-stuart-reges/

Building Java Programs - A Back to Basics Approach 5th Edition Stuart Reges
- eBook PDF

https://ebookluna.com/download/building-java-programs-a-back-to-basics-
approach-ebook-pdf-2/

Building Java Programs: A Back to Basics Approach 4th Edition (eBook PDF)

https://ebookluna.com/product/building-java-programs-a-back-to-basics-
approach-4th-edition-ebook-pdf/

(eBook PDF) Building Java Programs: A Back to Basics Approach 5th Edition

https://ebookluna.com/product/ebook-pdf-building-java-programs-a-back-to-
basics-approach-5th-edition/
College physics : a strategic approach 4th Edition Stuart Field - eBook PDF

https://ebookluna.com/download/college-physics-a-strategic-approach-ebook-
pdf/

Artificial Intelligence: A Modern Approach 4th Edition Stuart Russell -


eBook PDF

https://ebookluna.com/download/artificial-intelligence-a-modern-
approach-4th-edition-ebook-pdf/

(eBook PDF) Building Python Programs 1st Edition

https://ebookluna.com/product/ebook-pdf-building-python-programs-1st-
edition/

Java: A Beginner's Guide: Create, Compile, and Run Java Programs Today 9th
Edition Herbert Schildt - eBook PDF

https://ebookluna.com/download/java-a-beginners-guide-create-compile-and-
run-java-programs-today-ebook-pdf/

(eBook PDF) Introduction to Programming with Java: A Problem Solving


Approach 3rd Edition

https://ebookluna.com/product/ebook-pdf-introduction-to-programming-with-
java-a-problem-solving-approach-3rd-edition/
Building Java Programs
A Back to Basics Approach

Fourth Edition

Stuart Reges

University of Washington

Marty Stepp

Stanford University

Boston Columbus Indianapolis New York San Francisco Hoboken


Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal
Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore
Taipei Tokyo
Vice President, Editorial Director: Marcia Horton

Acquisitions Editor: Matt Goldstein

Editorial Assistant: Kristy Alaura

VP of Marketing: Christy Lesko

Director of Field Marketing: Tim Galligan

Product Marketing Manager: Bram Van Kempen

Field Marketing Manager: Demetrius Hall

Marketing Assistant: Jon Bryant

Director of Product Management: Erin Gregg

Team Lead, Program and Project Management: Scott Disanno

Program Manager: Carole Snyder

Project Manager: Lakeside Editorial Services L.L.C.

Senior Specialist, Program Planning and Support: Maura Zaldivar-Garcia

Cover Design: Joyce Wells

R&P Manager: Rachel Youdelman

R&P Project Manager: Timothy Nicholls

Inventory Manager: Meredith Maresca

Cover Art: Matt Walford/Cultura/Getty Images

Full-Service Project Management: Apoorva Goel/Cenveo Publisher


Services
Composition: Cenveo® Publisher Services

Printer/Binder: Edwards Brothers Malloy

Cover Printer: Phoenix Color

Text Font: Monotype

The authors and publisher of this book have used their best efforts in
preparing this book. These efforts include the development, research, and
testing of the theories and programs to determine their effectiveness. The
authors and publisher make no warranty of any kind, expressed or implied,
with regard to these programs or to the documentation contained in this book.
The authors and publisher shall not be liable in any event for incidental or
consequential damages in connection with, or arising out of, the furnishing,
performance, or use of these programs.

Copyright © 2017, 2014 and 2011 Pearson Education, Inc. or its affiliates.
All rights reserved. Printed in the United States of America. This publication
is protected by copyright, and permission should be obtained from the
publisher prior to any prohibited reproduction, storage in a retrieval system,
or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or otherwise. For information regarding
permissions, request forms and the appropriate contacts within the Pearson
Education Global Rights & Permissions department, please visit
www.pearsonhighed.com/permissions/.

Acknowledgements of third party content appear on pages 1193–1194, which


constitute an extension of this copyright page.

PEARSON, and MYPROGRAMMINGLAB are exclusive trademarks in the


U.S. and/or other countries owned by Pearson Education, Inc. or its affiliates.

Unless otherwise indicated herein, any third-party trademarks that may


appear in this work are the property of their respective owners and any
references to third-party trademarks, logos or other trade dress are for
demonstrative or descriptive purposes only. Such references are not intended
to imply any sponsorship, endorsement, authorization, or promotion of
Pearson's products by the owners of such marks, or any relationship between
the owner and Pearson Education, Inc. or its affiliates, authors, licensees or
distributors.

Library of Congress Cataloging-in-Publication Data

Names: Reges, Stuart, author. | Stepp, Martin, author.

Title: Building Java programs : a back to basics approach / Stuart Reges,


University of Washington; Marty Stepp, Stanford University.

Description: Fourth Edition. | Hoboken, NJ : Pearson, 2016.

Identifiers: LCCN 2015049340 | ISBN 9780134322766 (alk. paper)

Subjects: LCSH: Java (Computer program language)

Classification: LCC QA76.73.J38 R447 2016 | DDC 005.13/3—dc23 LC


record available at http://lccn.loc.gov/2015049340

10 9 8 7 6 5 4 3 2 1

ISBN 10: 0-13-432276-2

ISBN 13: 978-0-13-432276-6


Preface
The newly revised fourth edition of our Building Java Programs textbook is
designed for use in a two-course introduction to computer science. We have
class-tested it with thousands of undergraduates, most of whom were not
computer science majors, in our CS1-CS2 sequence at the University of
Washington. These courses are experiencing record enrollments, and other
schools that have adopted our textbook report that students are succeeding
with our approach.

Introductory computer science courses are often seen as “killer” courses with
high failure rates. But as Douglas Adams says in The Hitchhiker's Guide to
the Galaxy, “Don't panic.” Students can master this material if they can learn
it gradually. Our textbook uses a layered approach to introduce new syntax
and concepts over multiple chapters.

Our textbook uses an “objects later” approach where programming


fundamentals and procedural decomposition are taught before diving into
object-oriented programming. We have championed this approach, which we
sometimes call “back to basics,” and have seen through years of experience
that a broad range of scientists, engineers, and others can learn how to
program in a procedural manner. Once we have built a solid foundation of
procedural techniques, we turn to object-oriented programming. By the end
of the course, students will have learned about both styles of programming.

Here are some of the changes that we have made in the fourth edition:

New chapter on functional programming with Java 8. As explained


below, we have introduced a chapter that uses the new language features
available in Java 8 to discuss the core concepts of functional
programming.

New section on images and 2D pixel array manipulation. Image


manipulation is becoming increasingly popular, so we have expanded
our DrawingPanel class to include features that support manipulating
images as two-dimensional arrays of pixel values. This extra coverage
will be particularly helpful for students taking an AP/CS A course
because of the heavy emphasis on two-dimensional arrays on the AP
exam.

Expanded self-checks and programming exercises. Many chapters have


received new self-check problems and programming exercises. There
are roughly fifty total problems and exercises per chapter, all of which
have been class-tested with real students and have solutions provided for
instructors on our web site.

Since the publication of our third edition, Java 8 has been released. This new
version supports a style of programming known as functional programming
that is gaining in popularity because of its ability to simply express complex
algorithms that are more easily executed in parallel on machines with
multiple processors. ACM and IEEE have released new guidelines for
undergraduate computer science curricula, including a strong
recommendation to cover functional programming concepts.

We have added a new Chapter 19 that covers most of the functional concepts
from the new curriculum guidelines. The focus is on concepts, not on
language features. As a result, it provides an introduction to several new Java
8 constructs but not a comprehensive coverage of all new language features.
This provides flexibility to instructors since functional programming features
can be covered as an advanced independent topic, incorporated along the
way, or skipped entirely. Instructors can choose to start covering functional
constructs along with traditional constructs as early as Chapter 6. See the
dependency chart at the end of this section.

The following features have been retained from previous editions:

Focus on problem solving. Many textbooks focus on language details


when they introduce new constructs. We focus instead on problem
solving. What new problems can be solved with each construct? What
pitfalls are novices likely to encounter along the way? What are the most
common ways to use a new construct?

Emphasis on algorithmic thinking. Our procedural approach allows us to


emphasize algorithmic problem solving: breaking a large problem into
smaller problems, using pseudocode to refine an algorithm, and
grappling with the challenge of expressing a large program
algorithmically.

Layered approach. Programming in Java involves many concepts that


are difficult to learn all at once. Teaching Java to a novice is like trying
to build a house of cards. Each new card has to be placed carefully. If
the process is rushed and you try to place too many cards at once, the
entire structure collapses. We teach new concepts gradually, layer by
layer, allowing students to expand their understanding at a manageable
pace.

Case studies. We end most chapters with a significant case study that
shows students how to develop a complex program in stages and how to
test it as it is being developed. This structure allows us to demonstrate
each new programming construct in a rich context that can't be achieved
with short code examples. Several of the case studies were expanded
and improved in the second edition.

Utility as a CS1+CS2 textbook. In recent editions, we added chapters


that extend the coverage of the book to cover all of the topics from our
second course in computer science, making the book usable for a two-
course sequence. Chapters 12–19 explore recursion, searching and
sorting, stacks and queues, collection implementation, linked lists,
binary trees, hash tables, heaps, and more. Chapter 12 also received a
section on recursive backtracking, a powerful technique for exploring a
set of possibilities for solving problems such as 8 Queens and Sudoku.

Layers and Dependencies


Many introductory computer science books are language-oriented, but the
early chapters of our book are layered. For example, Java has many control
structures (including for-loops, while-loops, and if/else-statements), and
many books include all of these control structures in a single chapter. While
that might make sense to someone who already knows how to program, it can
be overwhelming for a novice who is learning how to program. We find that
it is much more effective to spread these control structures into different
chapters so that students learn one structure at a time rather than trying to
learn them all at once.

The following table shows how the layered approach works in the first six
chapters:

Control Programming
Chapter Data Input/Output
Flow Techniques
procedural
1 methods String literals println, print
decomposition
definite variables, local variables, class
2 loops expressions, constants,
(for) int, double pseudocode
console input, 2D
return
3 using objects parameters graphics
values
(optional)
conditional char pre/post conditions, printf
4
(if/else) throwing exceptions
indefinite
assertions, robust
5 loops boolean
programs
(while)
token/line-based file
6 Scanner file I/O
processing

Chapters 1–6 are designed to be worked through in order, with greater


flexibility of study then beginning in Chapter 7. Chapter 6 may be skipped,
although the case study in Chapter 7 involves reading from a file, a topic that
is covered in Chapter 6.

The following is a dependency chart for the book:


Supplements
http://www.buildingjavaprograms.com/

Answers to all self-check problems appear on our web site and are accessible
to anyone. Our web site has the following additional resources for students:

Online-only supplemental chapters, such as a chapter on creating


Graphical User Interfaces

Source code and data files for all case studies and other complete
program examples

The DrawingPanel class used in the optional graphics Supplement 3G

Our web site has the following additional resources for teachers:

PowerPoint slides suitable for lectures

Solutions to exercises and programming projects, along with homework


specification documents for many projects

Sample exams and solution keys

Additional lab exercises and programming exercises with solution keys

Closed lab creation tools to produce lab handouts with the instructor's
choice of problems integrated with the textbook

To access protected instructor resources, contact us at


authors@buildingjavaprograms.com. The same materials are also available at
http://www.pearsonhighered.com/cs-resources. To receive a password for this
site or to ask other questions related to resources, contact your Pearson sales
representative.

MyProgrammingLab
MyProgrammingLab is an online practice and assessment tool that helps
students fully grasp the logic, semantics, and syntax of programming.
Through practice exercises and immediate, personalized feedback,
MyProgrammingLab improves the programming competence of beginning
students who often struggle with basic concepts and paradigms of popular
high-level programming languages. A self-study and homework tool, the
MyProgrammingLab course consists of hundreds of small practice exercises
organized around the structure of this textbook. For students, the system
automatically detects errors in the logic and syntax of code submissions and
offers targeted hints that enable students to figure out what went wrong, and
why. For instructors, a comprehensive grade book tracks correct and
incorrect answers and stores the code inputted by students for review.

For a full demonstration, to see feedback from instructors and students, or to


adopt MyProgrammingLab for your course, visit the following web site:
http://www.myprogramminglab.com/

VideoNotes

We have recorded a series of instructional videos to accompany the textbook.


They are available at the following web site: www.pearsonhighered.com/cs-
resources

Roughly 3–4 videos are posted for each chapter. An icon in the margin of the
page indicates when a VideoNote is available for a given topic. In each video,
we spend 5–15 minutes walking through a particular concept or problem,
talking about the challenges and methods necessary to solve it. These videos
make a good supplement to the instruction given in lecture classes and in the
textbook. Your new copy of the textbook has an access code that will allow
you to view the videos.
Acknowledgments
First, we would like to thank the many colleagues, students, and teaching
assistants who have used and commented on early drafts of this text. We
could not have written this book without their input. Special thanks go to
Hélène Martin, who pored over early versions of our first edition chapters to
find errors and to identify rough patches that needed work. We would also
like to thank instructor Benson Limketkai for spending many hours
performing a technical proofread of the second edition.

Second, we would like to thank the talented pool of reviewers who guided us
in the process of creating this textbook:

Greg Anderson, Weber State University

Delroy A. Brinkerhoff, Weber State University

Ed Brunjes, Miramar Community College

Tom Capaul, Eastern Washington University

Tom Cortina, Carnegie Mellon University

Charles Dierbach, Towson University

H.E. Dunsmore, Purdue University

Michael Eckmann, Skidmore College

Mary Anne Egan, Siena College

Leonard J. Garrett, Temple University

Ahmad Ghafarian, North Georgia College & State University

Raj Gill, Anne Arundel Community College


Michael Hostetler, Park University

David Hovemeyer, York College of Pennsylvania

Chenglie Hu, Carroll College

Philip Isenhour, Virginia Polytechnic Institute

Andree Jacobson, University of New Mexico

David C. Kamper, Sr., Northeastern Illinois University

Simon G.M. Koo, University of San Diego

Evan Korth, New York University

Joan Krone, Denison University

John H.E.F. Lasseter, Fairfield University

Eric Matson, Wright State University

Kathryn S. McKinley, University of Texas, Austin

Jerry Mead, Bucknell University

George Medelinskas, Northern Essex Community College

John Neitzke, Truman State University

Dale E. Parson, Kutztown University

Richard E. Pattis, Carnegie Mellon University

Frederick Pratter, Eastern Oregon University

Roger Priebe, University of Texas, Austin

Dehu Qi, Lamar University


John Rager, Amherst College

Amala V.S. Rajan, Middlesex University

Craig Reinhart, California Lutheran University

Mike Scott, University of Texas, Austin

Alexa Sharp, Oberlin College

Tom Stokke, University of North Dakota

Leigh Ann Sudol, Fox Lane High School

Ronald F. Taylor, Wright State University

Andy Ray Terrel, University of Chicago

Scott Thede, DePauw University

Megan Thomas, California State University, Stanislaus

Dwight Tuinstra, SUNY Potsdam

Jeannie Turner, Sayre School

Tammy VanDeGrift, University of Portland

Thomas John VanDrunen, Wheaton College

Neal R. Wagner, University of Texas, San Antonio

Jiangping Wang, Webster University

Yang Wang, Missouri State University

Stephen Weiss, University of North Carolina at Chapel Hill

Laurie Werner, Miami University


Dianna Xu, Bryn Mawr College

Carol Zander, University of Washington, Bothell

Finally, we would like to thank the great staff at Pearson who helped produce
the book. Michelle Brown, Jeff Holcomb, Maurene Goo, Patty Mahtani,
Nancy Kotary, and Kathleen Kenny did great work preparing the first edition.
Our copy editors and the staff of Aptara Corp, including Heather Sisan, Brian
Baker, Brendan Short, and Rachel Head, caught many errors and improved
the quality of the writing. Marilyn Lloyd and Chelsea Bell served well as
project manager and editorial assistant respectively on prior editions. For
their help with the third edition we would like to thank Kayla Smith-Tarbox,
Production Project Manager, and Jenah Blitz-Stoehr, Computer Science
Editorial Assistant. Mohinder Singh and the staff at Aptara, Inc., were also
very helpful in the final production of the third edition. For their great work
on production of the fourth edition, we thank Louise Capulli and the staff of
Lakeside Editorial Services, along with Carole Snyder at Pearson. Special
thanks go to our lead editor at Pearson, Matt Goldstein, who has believed in
the concept of our book from day one. We couldn't have finished this job
without all of their hard work and support.

Stuart Reges

Marty Stepp
Break through
To Improving results

MyProgammingLab™
Through the power of practice and immediate personalized feedback,
MyProgrammingLab helps improve your students' performance.

Programming Practice
With MyProgrammingLab, your students will gain firs-hand programming
experience in an interactive online environment.

Immediate, Personalized Feedback


MyProgrammingLab automatically detects errors in the logic and syntax of
their code submission and offers targeted hints that enables students to figure
out what went wrong and why.

Graduated Complexity
MyProgrammingLab breaks down programming concepts into short,
understandable sequences of exercises. Within each sequence the level and
sophistication of the exercises increase gradually but steadily.
Dynamic Roster
Students' submissions are stored in a roster that indicates whether the
submission is correct, how many attempts were made, and the actual code
submissions from each attempt.

Pearson eText
The Pearson eText gives students access to their textbook anytime, anywhere

Step-By-Step Videonote Tutorials


These step-by-step video tutorials enhance the programming concepts
presented in select Pearson textbooks.
For more information and titles available with MyProgrammingLab, please
visit www.myprogramminglab.com.

Copyright © 2016 Pearson Education, Inc. or its affiliate(s). All rights


reserved. HELO88173 · 11/15

LOCATION OF VIDEO NOTES IN THE TEXT

www.pearsonhighered.com/cs-resources

Chapter 1 Pages 31, 40


Chapter 2 Pages 65, 74, 89, 97, 110
Chapter 3 Pages 141, 156, 161, 167
Chapter 3G Pages 197, 215
Chapter 4 Pages 243, 251, 278
Chapter 5 Pages 324, 327, 329, 333, 356
Chapter 6 Pages 396, 409, 423
Chapter 7 Pages 458, 465, 484, 505
Chapter 8 Pages 535, 547, 555, 568
Chapter 9 Pages 597, 610, 626
Chapter 10 Pages 672, 677, 686
Chapter 11 Pages 716, 729, 737
Chapter 12 Pages 764, 772, 809
Chapter 13 Pages 834, 837, 843
Chapter 14 Pages 889, 896
Chapter 15 Pages 930, 936, 940
Chapter 16 Pages 972, 979, 992
Chapter 17 Pages 1037, 1038, 1048
Chapter 18 Pages 1073, 1092
Brief Contents
1. Chapter 1 Introduction to Java Programming 1

2. Chapter 2 Primitive Data and Definite Loops 63

3. Chapter 3 Introduction to Parameters and Objects 137

4. Supplement 3G Graphics (Optional) 196

5. Chapter 4 Conditional Execution 238

6. Chapter 5 Program Logic and Indefinite Loops 315

7. Chapter 6 File Processing 387

8. Chapter 7 Arrays 443

9. Chapter 8 Classes 530

10. Chapter 9 Inheritance and Interfaces 587

11. Chapter 10 ArrayLists 662

12. Chapter 11 Java Collections Framework 715

13. Chapter 12 Recursion 754

14. Chapter 13 Searching and Sorting 832

15. Chapter 14 Stacks and Queues 884

16. Chapter 15 Implementing a Collection Class 922

17. Chapter 16 Linked Lists 965

18. Chapter 17 Binary Trees 1017


19. Chapter 18 Advanced Data Structures 1071

20. Chapter 19 Functional Programming with Java 1107

1. Appendix A Java Summary 1149

2. Appendix B The Java API Specification and Javadoc Comments 1164

3. Appendix C Additional Java Syntax 1170


Contents
1. Chapter 1 Introduction to Java Programming 1

1. 1.1 Basic Computing Concepts 2

1. Why Programming? 2

2. Hardware and Software 3

3. The Digital Realm 4

4. The Process of Programming 6

5. Why Java? 7

6. The Java Programming Environment 8

2. 1.2 And Now—Java 10

1. String Literals (Strings) 14

2. System.out.println 15

3. Escape Sequences 15

4. print versus println 17

5. Identifiers and Keywords 18

6. A Complex Example: DrawFigures1 20

7. Comments and Readability 21

3. 1.3 Program Errors 24

1. Syntax Errors 24
2. Logic Errors (Bugs) 28

4. 1.4 Procedural Decomposition 28

1. Static Methods 31

2. Flow of Control 34

3. Methods That Call Other Methods 36

4. An Example Runtime Error 39

5. 1.5 Case Study: DrawFigures 40

1. Structured Version 41

2. Final Version without Redundancy 43

3. Analysis of Flow of Execution 44

2. Chapter 2 Primitive Data and Definite Loops 63

1. 2.1 Basic Data Concepts 64

1. Primitive Types 64

2. Expressions 65

3. Literals 67

4. Arithmetic Operators 68

5. Precedence 70

6. Mixing Types and Casting 73

2. 2.2 Variables 74

1. Assignment/Declaration Variations 79
2. String Concatenation 82

3. Increment/Decrement Operators 84

4. Variables and Mixing Types 87

3. 2.3 The for Loop 89

1. Tracing for Loops 91

2. for Loop Patterns 95

3. Nested for Loops 97

4. 2.4 Managing Complexity 99

1. Scope 99

2. Pseudocode 105

3. Class Constants 108

5. 2.5 Case Study: Hourglass Figure 110

1. Problem Decomposition and Pseudocode 111

2. Initial Structured Version 113

3. Adding a Class Constant 114

4. Further Variations 117

3. Chapter 3 Introduction to Parameters and Objects 137

1. 3.1 Parameters 138

1. The Mechanics of Parameters 141

2. Limitations of Parameters 145


3. Multiple Parameters 148

4. Parameters versus Constants 151

5. Overloading of Methods 151

2. 3.2 Methods That Return Values 152

1. The Math Class 153

2. Defining Methods That Return Values 156

3. 3.3 Using Objects 160

1. String Objects 161

2. Interactive Programs and Scanner Objects 167

3. Sample Interactive Program 170

4. 3.4 Case Study: Projectile Trajectory 173

1. Unstructured Solution 177

2. Structured Solution 179

4. Supplement 3G Graphics (Optional) 196

1. 3G.1 Introduction to Graphics 197

1. DrawingPanel 197

2. Drawing Lines and Shapes 198

3. Colors 203

4. Drawing with Loops 206

5. Text and Fonts 210


6. Images 213

2. 3G.2 Procedural Decomposition with Graphics 215

1. A Larger Example: DrawDiamonds 216

3. 3G.3 Case Study: Pyramids 219

1. Unstructured Partial Solution 220

2. Generalizing the Drawing of Pyramids 222

3. Complete Structured Solution 223

5. Chapter 4 Conditional Execution 238

1. 4.1 if/else Statements 239

1. Relational Operators 241

2. Nested if/else Statements 243

3. Object Equality 250

4. Factoring if/else Statements 251

5. Testing Multiple Conditions 253

2. 4.2 Cumulative Algorithms 254

1. Cumulative Sum 254

2. Min/Max Loops 256

3. Cumulative Sum with if 260

4. Roundoff Errors 262

3. 4.3 Text Processing 265


1. The char Type 265

2. char versus int 266

3. Cumulative Text Algorithms 267

4. System.out.printf 269

4. 4.4 Methods with Conditional Execution 274

1. Preconditions and Postconditions 274

2. Throwing Exceptions 274

3. Revisiting Return Values 278

4. Reasoning about Paths 283

5. 4.5 Case Study: Body Mass Index 285

1. One-Person Unstructured Solution 286

2. Two-Person Unstructured Solution 289

3. Two-Person Structured Solution 291

4. Procedural Design Heuristics 295

6. Chapter 5 Program Logic and Indefinite Loops 315

1. 5.1 The while Loop 316

1. A Loop to Find the Smallest Divisor 317

2. Random Numbers 320

3. Simulations 324

4. do/while Loop 325


2. 5.2 Fencepost Algorithms 327

1. Sentinel Loops 329

2. Fencepost with if 330

3. 5.3 The boolean Type 333

1. Logical Operators 335

2. Short-Circuited Evaluation 338

3. boolean Variables and Flags 342

4. Boolean Zen 344

5. Negating Boolean Expressions 347

4. 5.4 User Errors 348

1. Scanner Lookahead 349

2. Handling User Errors 351

5. 5.5 Assertions and Program Logic 353

1. Reasoning about Assertions 355

2. A Detailed Assertions Example 356

6. 5.6 Case Study: NumberGuess 361

1. Initial Version without Hinting 361

2. Randomized Version with Hinting 363

3. Final Robust Version 367

7. Chapter 6 File Processing 387


1. 6.1 File-Reading Basics 388

1. Data, Data Everywhere 388

2. Files and File Objects 388

3. Reading a File with a Scanner 391

2. 6.2 Details of Token-Based Processing 396

1. Structure of Files and Consuming Input 398

2. Scanner Parameters 403

3. Paths and Directories 404

4. A More Complex Input File 407

3. 6.3 Line-Based Processing 409

1. String Scanners and Line/Token Combinations 410

4. 6.4 Advanced File Processing 415

1. Output Files with PrintStream 415

2. Guaranteeing That Files Can Be Read 420

5. 6.5 Case Study: Zip Code Lookup 423

8. Chapter 7 Arrays 443

1. 7.1 Array Basics 444

1. Constructing and Traversing an Array 444

2. Accessing an Array 448

3. A Complete Array Program 451


4. Random Access 455

5. Arrays and Methods 458

6. The For-Each Loop 461

7. Initializing Arrays 463

8. The Arrays Class 464

2. 7.2 Array-Traversal Algorithms 465

1. Printing an Array 466

2. Searching and Replacing 468

3. Testing for Equality 471

4. Reversing an Array 472

5. String Traversal Algorithms 477

6. Functional Approach 478

3. 7.3 Reference Semantics 479

1. Multiple Objects 481

4. 7.4 Advanced Array Techniques 484

1. Shifting Values in an Array 484

2. Arrays of Objects 488

3. Command-Line Arguments 490

4. Nested Loop Algorithms 490

5. 7.5 Multidimensional Arrays 492


1. Rectangular Two-Dimensional Arrays 492

2. Jagged Arrays 494

6. 7.6 Arrays of Pixels 499

7. 7.7 Case Study: Benford's Law 504

1. Tallying Values 505

2. Completing the Program 509

9. Chapter 8 Classes 530

1. 8.1 Object-Oriented Programming 531

1. Classes and Objects 532

2. Point Objects 534

2. 8.2 Object State and Behavior 535

1. Object State: Fields 536

2. Object Behavior: Methods 538

3. The Implicit Parameter 541

4. Mutators and Accessors 543

5. The toString Method 545

3. 8.3 Object Initialization: Constructors 547

1. The Keyword this 552

2. Multiple Constructors 554

4. 8.4 Encapsulation 555


1. Private Fields 556

2. Class Invariants 562

3. Changing Internal Implementations 566

5. 8.5 Case Study: Designing a Stock Class 568

1. Object-Oriented Design Heuristics 569

2. Stock Fields and Method Headers 571

3. Stock Method and Constructor Implementation 573

10. Chapter 9 Inheritance and Interfaces 587

1. 9.1 Inheritance Basics 588

1. Nonprogramming Hierarchies 589

2. Extending a Class 591

3. Overriding Methods 595

2. 9.2 Interacting with the Superclass 597

1. Calling Overridden Methods 597

2. Accessing Inherited Fields 598

3. Calling a Superclass's Constructor 600

4. DividendStock Behavior 602

5. The Object Class 604

6. The equals Method 605

7. The instanceof Keyword 608


3. 9.3 Polymorphism 610

1. Polymorphism Mechanics 613

2. Interpreting Inheritance Code 615

3. Interpreting Complex Calls 617

4. 9.4 Inheritance and Design 620

1. A Misuse of Inheritance 620

2. Is-a Versus Has-a Relationships 623

3. Graphics2D 624

5. 9.5 Interfaces 626

1. An Interface for Shapes 627

2. Implementing an Interface 629

3. Benefits of Interfaces 632

6. 9.6 Case Study: Financial Class Hierarchy 634

1. Designing the Classes 635

2. Redundant Implementation 639

3. Abstract Classes 642

11. Chapter 10 ArrayLists 662

1. 10.1 ArrayLists 663

1. Basic ArrayList Operations 664

2. ArrayList Searching Methods 667


3. A Complete ArrayList Program 670

4. Adding to and Removing from an ArrayList 672

5. Using the For-Each Loop with ArrayLists 676

6. Wrapper Classes 677

2. 10.2 The Comparable Interface 680

1. Natural Ordering and compareTo 682

2. Implementing the Comparable Interface 686

3. 10.3 Case Study: Vocabulary Comparison 692

1. Some Efficiency Considerations 692

2. Version 1: Compute Vocabulary 695

3. Version 2: Compute Overlap 698

4. Version 3: Complete Program 703

12. Chapter 11 Java Collections Framework 715

1. 11.1 Lists 716

1. Collections 716

2. LinkedList versus ArrayList 717

3. Iterators 720

4. Abstract Data Types (ADTs) 724

5. LinkedList Case Study: Sieve 726

2. 11.2 Sets 729


1. Set Concepts 730

2. TreeSet versus HashSet 732

3. Set Operations 733

4. Set Case Study: Lottery 735

3. 11.3 Maps 737

1. Basic Map Operations 738

2. Map Views (keySet and values) 740

3. TreeMap versus HashMap 741

4. Map Case Study: WordCount 742

5. Collection Overview 745

13. Chapter 12 Recursion 754

1. 12.1 Thinking Recursively 755

1. A Nonprogramming Example 755

2. An Iterative Solution Converted to Recursion 758

3. Structure of Recursive Solutions 760

2. 12.2 A Better Example of Recursion 762

1. Mechanics of Recursion 764

3. 12.3 Recursive Functions and Data 772

1. Integer Exponentiation 772

2. Greatest Common Divisor 775


3. Directory Crawler 781

4. Helper Methods 785

4. 12.4 Recursive Graphics 788

5. 12.5 Recursive Backtracking 792

1. A Simple Example: Traveling North/East 793

2. 8 Queens Puzzle 798

3. Solving Sudoku Puzzles 805

6. 12.6 Case Study: Prefix Evaluator 809

1. Infix, Prefix, and Postfix Notation 809

2. Evaluating Prefix Expressions 810

3. Complete Program 813

14. Chapter 13 Searching and Sorting 832

1. 13.1 Searching and Sorting in the Java Class Libraries 833

1. Binary Search 834

2. Sorting 837

3. Shuffling 838

4. Custom Ordering with Comparators 839

2. 13.2 Program Complexity 843

1. Empirical Analysis 846

2. Complexity Classes 850


3. 13.3 Implementing Searching and Sorting Algorithms 852

1. Sequential Search 853

2. Binary Search 854

3. Recursive Binary Search 857

4. Searching Objects 860

5. Selection Sort 861

4. 13.4 Case Study: Implementing Merge Sort 864

1. Splitting and Merging Arrays 865

2. Recursive Merge Sort 868

3. Complete Program 871

15. Chapter 14 Stacks and Queues 884

1. 14.1 Stack/Queue Basics 885

1. Stack Concepts 885

2. Queue Concepts 888

2. 14.2 Common Stack/Queue Operations 889

1. Transferring Between Stacks and Queues 891

2. Sum of a Queue 892

3. Sum of a Stack 893

3. 14.3 Complex Stack/Queue Operations 896

1. Removing Values from a Queue 896


2. Comparing Two Stacks for Similarity 898

4. 14.4 Case Study: Expression Evaluator 900

1. Splitting into Tokens 901

2. The Evaluator 906

16. Chapter 15 Implementing a Collection Class 922

1. 15.1 Simple ArrayIntList 923

1. Adding and Printing 923

2. Thinking about Encapsulation 929

3. Dealing with the Middle of the List 930

4. Another Constructor and a Constant 935

5. Preconditions and Postconditions 936

2. 15.2 A More Complete ArrayIntList 940

1. Throwing Exceptions 940

2. Convenience Methods 943

3. 15.3 Advanced Features 946

1. Resizing When Necessary 946

2. Adding an Iterator 948

4. 15.4 ArrayList<E> 954

17. Chapter 16 Linked Lists 965

1. 16.1 Working with Nodes 966


1. Constructing a List 967

2. List Basics 969

3. Manipulating Nodes 972

4. Traversing a List 975

2. 16.2 A Linked List Class 979

1. Simple LinkedIntList 979

2. Appending add 981

3. The Middle of the List 985

3. 16.3 A Complex List Operation 992

1. Inchworm Approach 997

4. 16.4 An IntList Interface 998

5. 16.5 LinkedList<E> 1001

1. Linked List Variations 1002

2. Linked List Iterators 1005

3. Other Code Details 1007

18. Chapter 17 Binary Trees 1017

1. 17.1 Binary Tree Basics 1018

1. Node and Tree Classes 1021

2. 17.2 Tree Traversals 1022

1. Constructing and Viewing a Tree 1028


3. 17.3 Common Tree Operations 1037

1. Sum of a Tree 1037

2. Counting Levels 1038

3. Counting Leaves 1040

4. 17.4 Binary Search Trees 1041

1. The Binary Search Tree Property 1042

2. Building a Binary Search Tree 1044

3. The Pattern x = change(x) 1048

4. Searching the Tree 1051

5. Binary Search Tree Complexity 1055

5. 17.5 SearchTree<E> 1056

19. Chapter 18 Advanced Data Structures 1071

1. 18.1 Hashing 1072

1. Array Set Implementations 1072

2. Hash Functions and Hash Tables 1073

3. Collisions 1075

4. Rehashing 1080

5. Hashing Non-Integer Data 1083

6. Hash Map Implementation 1086

2. 18.2 Priority Queues and Heaps 1087


1. Priority Queues 1087

2. Introduction to Heaps 1089

3. Removing from a Heap 1091

4. Adding to a Heap 1092

5. Array Heap Implementation 1094

6. Heap Sort 1098

20. Chapter 19 Functional Programming with Java 8 1107

1. 19.1 Effect-Free Programming 1108

2. 19.2 First-Class Functions 1111

1. Lambda Expressions 1114

3. 19.3 Streams 1117

1. Basic Idea 1117

2. Using Map 1119

3. Using Filter 1120

4. Using Reduce 1122

5. Optional Results 1123

4. 19.4 Function Closures 1124

5. 19.5 Higher-Order Operations on Collections 1127

1. Working with Arrays 1128

2. Working with Lists 1129


3. Working with Files 1133

6. 19.6 Case Study: Perfect Numbers 1134

1. Computing Sums 1135

2. Incorporating Square Root 1138

3. Just Five and Leveraging Concurrency 1141

1. Appendix A Java Summary 1149

2. Appendix B The Java API Specification and Javadoc Comments 1164

3. Appendix C Additional Java Syntax 1170

4. Index 1179

5. Credits 1193
Chapter 1 Introduction to Java
Programming
1. 1.1 Basic Computing Concepts

1. Why Programming?

2. Hardware and Software

3. The Digital Realm

4. The Process of Programming

5. Why Java?

6. The Java Programming Environment

2. 1.2 And Now—Java

1. String Literals (Strings)

2. System.out.println

3. Escape Sequences

4. print versus println

5. Identifiers and Keywords

6. A Complex Example: DrawFigures1

7. Comments and Readability

3. 1.3 Program Errors

1. Syntax Errors
2. Logic Errors (Bugs)

4. 1.4 Procedural Decomposition

1. Static Methods

2. Flow of Control

3. Methods That Call Other Methods

4. An Example Runtime Error

5. 1.5 Case Study: DrawFigures

1. Structured Version

2. Final Version without Redundancy

3. Analysis of Flow of Execution

Introduction
This chapter begins with a review of some basic terminology about
computers and computer programming. Many of these concepts will come up
in later chapters, so it will be useful to review them before we start delving
into the details of how to program in Java.

We will begin our exploration of Java by looking at simple programs that


produce output. This discussion will allow us to explore many elements that
are common to all Java programs, while working with programs that are
fairly simple in structure.

After we have reviewed the basic elements of Java programs, we will explore
the technique of procedural decomposition by learning how to break up a
Java program into several methods. Using this technique, we can break up
complex tasks into smaller subtasks that are easier to manage and we can
avoid redundancy in our program solutions.
Discovering Diverse Content Through
Random Scribd Documents
The Story of a Wandering Sheep
The sheep is generally regarded as a very uninteresting animal, but
occasionally there is an exception.

A man who had a small farm, stocked mostly with cattle, had a few
sheep which he kept in a small pasture by themselves. Among this flock
was a young masculine who had gradually acquired the opinion that he
was an unusually brilliant and promising sheep. In order to exhibit the
good opinion he had of himself he developed a pugnacious tendency
and a disposition to wander about. Escaping from the pasture, he was
reported one day as being a trespasser on the farm of a near neighbor.

The following evening the owner of the young sheep proceeded to the
neighbor’s farm to reclaim the wanderer and put him back where he
belonged. It had been a showery day and everything was saturated
with rain. Approaching the farmyard where the strayed sheep was
reported to be, the owner saw the wife of the farmer engaged in
milking a cow. Incidentally, he saw the sheep on the other side of the
cow from the matron. And almost immediately he saw other
developments. The sheep had been regarded with strong disfavor by
the strange cows with which he was surrounded and with a spirit of
resentment he suddenly started head down at the cow being milked.
Although the lady who was busily engaged in the milking process was
totally unconscious of what was happening, it was not so with the cow.
Just at the psychological moment, the cow sprang forward and the
sheep came in violent contact with the lady and the milk pail. The
impact was so great that the woman was thrown over backward in the
soft mud of the barnyard, the contents of the pail being liberally
distributed about her robust person.

Although the physical injury was not serious, the damage to the lady’s
dignity was such that the owner of the sheep decided that it was a very
inappropriate time to claim his missing property and hastily beat his
retreat to make his reappearance when the lady’s wrath had somewhat
subsided.
While the lady sheep is a model of amiability under practically all
circumstances, as before suggested, the male of the species develops
egotism at a very early date; he also develops a tendency to resent
anything and everything that reflects upon his dignity. So, while it is
entirely appropriate to emphasize the educational advantages of farm
life to growing boys and girls as calculated to develop many desirable
qualities, it is easily possible for such contact to result disastrously to
the young male sheep as evidenced by the following depressing
incident.

The Young and “Self-Centered” Ram


Another young and somewhat self-centered male sheep had been
tantalized by small boys until his dignity was deeply wounded. He was
one of two or three that followed a herd of cows around a large pasture
on a dairy farm. In a certain portion of this enclosure there were some
wild raspberry bushes, and a certain estimable scrub woman of the
neighborhood went to the pasture one day to pick some berries. There
was something about this woman that didn’t meet with the approval of
the young sheep and he made a sudden attack which resulted in the
loss of the berries and incidentally produced a few bruises. The woman
escaped from the pasture and went to the farmhouse and expressed
her indignation that any such wild beast should be allowed to be at
large to commit assaults on the neighbors. The owner of the sheep, a
very amiable man, apologized profusely and directed that the animal be
kept in confinement, at least until the berry season was over. He was
therefore confined in a ramshackle stable, tied behind a loose board.

Enter the villains of this tragedy! four small boys, each armed with a
small, harmless, but otherwise objectionable birch stick. The prisoner
glared at them, whereupon one after another they advanced and
tapped the young ram playfully on the nose with their sticks. In violent
resentment he would lunge forward against the loose board, making a
tremendous racket. Although this enterprise only lasted a few minutes
before it became tiresome to the gamins in question, it was sufficient to
completely wreck whatever might have been previously left of this
sheep’s amiability. He became an anarchist then and there.

The next morning was rainy and there was no probability that any berry
pickers would visit the pasture, so the sheep which had expressed his
dissatisfaction by many loud protests during the previous days, was
gladly released to be allowed to go at large. It was here that Grim
Tragedy stalked forth. The farmyard was a quagmire as a result of the
rain and as one of the older “boys” started to carefully pick his way
through the mud with two brimming milk pails, the sheep caught sight
of him and decided that this was the time to avenge some of those
insults of the day before. Just as the young man was crossing the
deepest portion of the bog, he was made the victim of a rear attack.
The result can easily be imagined. In his great wrath, extricating
himself, he cornered the pugnacious sheep and changed him into
mutton in a very few seconds.

It has been stated before that contact with the various animal
inhabitants of a well equipped farm is in itself an educational process of
no small value; it may be added that there is often as much diversion
as education in these experiences.

The Sudden Enlightenment of the Young Pup


Much has been written of geese and their superior mental qualities as
compared with other fowl. It is true that they are wise in certain ways
and that the average hen is very stupid by comparison. But the hen is a
never-ending source of amusement to many people, especially when
zealously engaged in bringing up a brood. It might be almost assumed
that the hen has reasoning power at times, as for example:
A collie puppy was added to the equipment of a certain farm and after
a few days he began to make a general tour of investigation. He
seemed to find the young chickens about as interesting as anything and
while doing them no injury he would nose them about to the terror of
the chickens and the great indignation of the mother hens. At a time of
emergency some noble figure should always step forward and this
emergency was no exception. Early one morning the pup was seen
flying across the yard, uttering the most agonizing cries, one of the
maternal hens standing squarely in the middle of his back, incidentally
giving him her opinion of dogs in general and himself in particular. The
hen hopped off and went back to the chickens and the puppy was
absolutely cured. He had no further curiosity in that direction.

A Hen Heroine
Another true instance of hen wisdom deals with an ancient female of
that species, who had lived to ripe old age because of her
extraordinarily good judgment in bringing up chickens. One day the
owner heard a great outcry. Looking out she saw the hen engaged in a
vigorous battle with a crow. It may be incidentally mentioned that while
the crow does not ordinarily molest young chickens, there are
exceptions and this was a very bold marauder indeed. However, he
reckoned without his host, as the old hen had lived long enough and
had acquired sufficient knowledge of crow depravity to meet the
emergency in a business-like way. She viciously attacked and continued
to fight the crow, who was unable to get in a position to fly away, until
help arrived and the crow was promptly dispatched. No young fowl, a
year or two old, would have had the requisite courage, but this hen,
who had long since passed the stage of edibility as poultry, had
gradually developed the intelligence and pluck to fight the crow with his
own weapons.
It is often pathetic to see how difficult it is for a normal small boy who
lives in the crowded sections of a big city to find any legitimate outlet
for his energies. He grows up with relatively few opportunities to
develop any sense of personal responsibility. Not so the boy on the New
England farm. If it is a real farm and conducted as a means of
livelihood for the family, responsibility is constantly camping on his trail.

The Story of the “Lolling” Horse


Two farm boys about ten years of age who lived in a period when there
were no automobiles, had early been accustomed to the care of farm
animals and had incidentally had some casual experiences in driving
horses.

One day they were given permission to visit a married cousin of one of
the boys at her home some miles away. For the first time in their young
lives they were allowed to start out alone with a horse and buggy. It
was a great occasion and they began their journey with much
anticipation, but before they had gone a mile Dull Care had settled
upon them and attended them continuously until their return in the
early evening.

Only a short time before, one of the boys heard a distressing story
relating to an ox that had died from being overheated. A premonitory
symptom of the approaching demise of the ox had been that he “lolled.”
This had made a deep impression on the boy who heard the story.

It would hardly seem to be necessary to explain that of all domestic


animals, the horse is the only one which perspires freely. This affords
relief to the horse when hard at work on a warm day. And it of course
provides a clue to his condition. The teamster will not push his
overheated team horses too hard. With the ox team it is different. Heat
exhaustion may be near and still there will be little or no evidence of
such condition, the most characteristic symptom, however, being the
tendency of the ox to “loll” or allow his tongue to protrude from his
mouth in his panting efforts to perform his task.
Therefore with this bovine tragedy fresh in mind it is easy to imagine
the consternation of these two holiday seekers, when, after jogging
along at a comfortable pace for a mile or two, the horse, beginning to
show some evidence of perspiration, and turning his head to snap at a
pestiferous fly, disclosed the fact that his tongue was protruding. The
boys looked at each other with horror. What had they done? The none
too reluctant animal was restrained to a slow walk and after a time the
boys saw with great relief that he had his tongue back in his mouth
where a horse’s tongue ought to be. They slowly made their way to the
home of their hostess and, not wishing to disclose the fact that they
had been overdriving their horse, they carefully refrained from speaking
of the heavy weight of anxiety with which they were oppressed. They
made an early start for home and after a slow, tedious journey in the
hottest part of the day, they arrived and turned over their horse
apparently as sound as when they had taken him in charge. Their
mysterious manner, however, caused interest and when the facts were
made clear, it afforded much amusement to the two families who could
not refrain from making subsequent allusions to “the lolling horse.” It
may be said in explanation that the horse in question merely had a little
habit of occasionally protruding his tongue, which the boys had never
happened to notice before. It may be taken for granted, however, that
the sense of responsibility thus displayed by the boys, was not lost sight
of by their elders.

And it may also be assumed that the next time that horse was driven
by those boys, he was not permitted to lag on his journey.

The common exchange of farm implements, wagons, or sleds, in rural


New England, does not generally include the loaning of team horses.
The average farm horse, as before suggested, has his special
individuality, and it is not a difficult thing for a work horse to get
demoralized in the hands of a strange driver. In such cases, he may
become very reluctant to take hold and pull a heavy load.
The Farmer Who Borrowed the Blind Horse
A certain farmer, however, had a horse which he was always ready to
turn over to any responsible borrower. The horse was blind and his age
had long been a matter of conjecture. One day a neighbor, unaware of
the extraordinary docility of this poor, blind beast, asked if he could
have the horse to drive eight or ten miles on a necessary errand.
Permission was readily granted and he led the horse home, harnessed
him, and started out. He succeeded in getting back home in the middle
of the night. The next morning he led the horse back to the owner.

“It is my custom,” said he, “to pay for a borrowed horse in praising, but
this time I want to pay some other way.”

Just how much blindness had to do with the total lack of courage of this
borrowed horse would be hard to say, but it was probably a
contributing factor.

It is sometimes hinted that people who have retained health and


comparative youthfulness to an advanced age, have reason to thank
themselves for the excellent judgment they have manifested in avoiding
undue exertion rather than for any unusual inherited vigor. There are,
however, other factors besides the avoidance of physical labor to be
considered, as for example, cheerful temperament and an active, alert
mind. This latter quality seems to hold good with the animal creation as
shown by the following example.

The Lame Horse That Was Suddenly Cured


A young couple, who had arrived at a state of mind in which there was
considerable mutual interest, found it very desirable one day to take a
little drive. Their parents lived on two adjoining farms and it was a busy
season. Spare horses were scarce. Finally an agreement was reached.
The young lady agreed to furnish horse and harness if her companion
would furnish the buggy. This seemed to be a practical arrangement
and they started gayly out on their trip. After lunch in town, there
seemed to be nothing else to do but start for home, but they were in
no great hurry to arrive there, so at a certain turn in the road they
decided to make a detour.

The little Morgan mare of quite advanced age, contributed by the young
lady as her quota of the team, had very peculiar ideas. She thoroughly
disapproved of the trip in the first place, and secondly the young man’s
driving was also entirely different from anything she was accustomed
to. At the prospect of returning home, however, she seemed to cheer
up amazingly until she found herself being turned off on the side road.
She moped along for a few yards and then began to be very lame.

“This is a nice prospect!” said the driver. “I think we had better turn
straight around and get home, if we can.”

The young lady was quite well acquainted with the little white mare.

“Let me take those reins,” said she.

She took over the reins and gave the poor, lame horse a couple of
slashes with the whip and a miracle was performed. The lameness was
cured in an instant.

One of the most frequent tragedies of agricultural life is where some


farmer allows himself to feel that he has somehow lost a considerable
part of the pleasures of life by living remote from town. In such a case
the farmer, if well to do, may dispose of his farm and move to a nearby
village. And then, far too often, physical and even mental degeneration
will soon be in evidence. Lack of occupation is no doubt a considerable
factor, but the loss of the interest and congenial companionship
associated with domestic animals is probably no small item in this
disintegration.
In the consideration of animal life and its influence upon farm
environment, the wild birds should not be overlooked. As with the
human race, these birds present the varying characteristics of those
who are helpful and popular and those who constitute a problem.

The Bird Policeman


The crow is both a pest and a useful citizen. He is not nearly as popular
with the average farmer as he ought to be. It is the old story of the
roughneck’s total contempt for the opinion of his neighbors, human or
otherwise. The crow’s attitude is in general as follows: “You can’t put
anything over on me.” He is an ardent believer in “collective bargaining”
and when it is desirable to raid a field of ripe corn, the entire crow
colony is carefully organized for the purpose. Pickets will be established
to warn of the approach of any man with a gun.

But, however sardonic may be the attitude of Mr. Crow toward the poor,
plodding human farmers, he is quick to recognize his master, the
kingbird.

In a certain farmyard the crows and hawks had established a reign of


terror among the hens and chickens. Broods of chickens would be
depleted one by one until there were few survivors and the women of
the household became thoroughly exasperated. This went on to a
greater or less extent for several years. One bright June morning a
certain Mr. and Mrs. Kingbird arrived from a more southern clime and
looked the premises over. They decided that there was an excellent
opportunity to establish a home in one of the shade trees. They had
hardly got at work, however, before the male bird found it necessary to
take up a certain line of police duties. He discovered that the crows and
hawks had been making themselves very much at home in that
immediate neighborhood.

Within twenty-four hours the word had gone around to all the
marauders, and for years thereafter they never came near those
premises again. Each season the kingbird and his wife would come
back. That was sufficient protection for the young chickens who could
scratch about within the limits of their enclosure with perfect safety. It
can be taken for granted that everything was done by the owners of
the farm to make it pleasant for the bird policeman, who by his
extraordinary activities and fearlessness strikes terror to the heart of
the swiftest hawk, lest he be blinded by one of the lightning dashes of
the kingbird who always aims for the eyes.

The Evicted Swallows


At the same farm some swallows had established a system of
commodious mud dwellings under the eaves of the south and east side
of the barn. They occupied these premises year after year with
apparent satisfaction. One spring they were abruptly and summarily
dispossessed, although allowed to re-establish themselves on the other
side of the building. This is but a mere detail in bird life. The warm
southeastern exposure looked good to some bluebirds and they
promptly evicted those who had apparently secured the right of
possession by a long lease.

The Proprietary Attitude of the Robins


Robins, to most people, are merely robins. It would surprise the
average city inhabitant however, perhaps, to know that even the robin
may be individualized by farm dwellers, so that a certain old cock robin
who has been coming back, presumably with the same wife, year after
year, is promptly recognized on his arrival. In advanced years the cock
robin sometimes seems to develop obesity or at least great abdominal
extension, which may quite naturally be due to gradual indisposition to
labor but with no compensating tendency to reduce rations. This is,
however, so frequently observed in other male bipeds that it should not
occasion surprise.
The robin is perhaps the most popular of birds in the rural districts. It is
an unwritten law among native New Englanders that they shall not be
harassed or molested. The house cat which has been detected catching
a robin is in great disfavor immediately.

About the first sure indication of actual spring in this section is the
appearance of these welcome birds whose cheerfulness seems to be
contagious. They seem to be socially inclined toward humans and are
quite apt to locate their nests in close proximity to some farmhouse.
Indeed at times they seem to assume a rather proprietary attitude
toward the farm owners themselves, as shown by the following typical
incident.

One sultry day in July, it was noted at a certain farmhouse, that there
seemed to be considerable excitement among the robins. They were
unusually vociferous and someone wise to their habits suggested that
probably the young birds were about ready to make their first trial
flights. On the Sunday morning in question, most of the family had
gone to church when a certain slacker, who was left behind, took his
comfortable seat on the porch facing the lawn. The house dog was
lying on the grass nearby and all was quiet among the robins with one
exception. The exception was expressing high disapproval of
something. Suddenly there was the chatter of a squirrel in a clump of
trees a short distance away, and the dog arose to his feet and started
leisurely down to investigate. When he had gone about fifty feet there
suddenly developed a perfect din of protest, several robins joining in
the chorus to explain to the dog how unwelcome he was and no doubt
including various other uncomplimentary comments.

It was plainly depressing to the dog; he had had no quarrel with the
robins and saw no reason why they should talk to him in such abusive
terms. He came dejectedly back to his original location and lay down.
The chorus of disfavor stopped. Meantime, however, the robin in the
tree directly in front of the porch continued his tirade. Finally the dog
again arose and went around the corner, the man on the porch decided
to go in the house, and immediately all clamour ceased.
The Haunted Cat
At another farmhouse there were two well fed and properly cared for
cats actively engaged in the ever necessary warfare against mice. A
colony of swallows had built their nests under the eaves of a large barn.
So far as the human inhabitants of the farm could know there was no
essential difference in the moral characters of the two cats. But while
one of these cats could circulate around the buildings and no swallow
would seem to take any interest in the matter, as soon as the other cat
made her appearance in the space between the house and barn,
various active members of the swallow colony would immediately issue
forth from their retreat and proceed to swoop around and around the
cat a few feet from the ground, to her great discomfiture and
embarrassment. It became practically impossible for the cat to go out
of doors without undergoing this ordeal. She became a nervous wreck
and finally had to avoid this open area and take her promenades in
another direction.

It would be interesting to know just why the swallows made such a


discrimination between the two cats. Possibly the object of their
resentment had some time succeeded in capturing one of the birds, but
such an achievement by a cat is not very common, as the swallows are
extremely agile and capable of keeping out of reach. And if one cat had
become unpopular for this cause, why should not the swallows have
adopted aggressive and protective tactics toward the other cat who
might naturally be expected to follow the same predatory instinct if
given the opportunity?

To people who have spent their entire lifetime in the city, these
incidents of animal life might easily seem to be mostly imaginary, but to
those who are of receptive mind and keep a watchful eye upon the
various activities of the animal creation as revealed to them by
residence in the open country, there is presented a panorama of
individual traits, numerous and delightfully varied.
CHAPTER VII
Legends of Rural Spooks

It must be regretfully stated that the old time folklore of the supposed
supernatural has apparently vanished from modern New England.
Skepticism has seized upon the present generation and such genuine
unalloyed ghost stories as still persist are regarded as the harmless
delusions of old age. Thus, much that furnished thrills in earlier days
has departed.

They were creepy enough, those ancient tales. And in most instances
they were vouched for as strictly true by people whose reputations for
veracity were beyond dispute.

The Ghost in the Milk Dairy


Take the story of the milk pans as an example. The people who
occupied the milk pan infested residence were an intelligent church
going family of the highest standing. They were not superstitious and in
fact regarded their spooky experiences as a joke. They had a dairy farm
at a period when cream separators were unknown.

The process at that time was to “set” the milk in shallow tin pans and
skim off the cream when the milk had become sour. The cream was
then made into butter. Where there were quite a number of cows, a
considerable stack of these tin pans was required. Such as were not in
use would be placed in an orderly pile on a high shelf in the milk room.

Therefore, it can be readily understood that if one of these pans was to


slide off the shelf to the floor, it would make a loud noise.
Now, suppose the farmer and his family were sitting around the
evening lamp and all at once an unearthly din in the milk room should
indicate that a dozen or perhaps two dozen of those six-quart milk pans
had rolled from the top shelf to the floor, we would naturally expect one
or more members of the family to go at once to investigate.

Well, this highly respectable and truthful family would do nothing of the
kind. They would remain quietly reading the weekly paper, or knitting,
or popping corn, according to age and disposition; because they knew
no milk pans had stirred an inch. It was merely the spook amusing
himself.

The Spook Story of the Runaway Horse


A family lived on a back hilly road, and where the highway passed their
house it was quite steep. Comparatively few teams would be seen
during the day and still fewer would be abroad at night. It therefore
might be expected that when all the sounds of a horse galloping wildly
down the road with a rattling wagon at his heels should be heard, the
people would rush to the windows and doors to find out whose horse
was subjecting his driver to probable injury or sudden death; but they
didn’t—at least after the first few times. They knew no horse was
running away; it was only the spook.

And still there are people in this age of jazz who think the “old times”
had no excitement.

Most of the practical jokes of the spook were harmless, but in a given
instance he seems to have gone rather too far.

Table Tipping and a Victim


As could be expected a certain number of people were disposed to take
these “manifestations” quite seriously, regardless of the ridicule of their
neighbors. A group of these seekers after occult knowledge had
gathered one evening to engage in their favorite avocation of “table
tipping,” and were unusually favored with “signs.” The small table
around which they were seated became so totally unmindful of the
force of gravity that a recent novitiate of corpulent figure was induced
to seat himself upon it to keep it in place. No sooner had he taken his
position than the table began to float about the room.

It was a triumphant moment for the believers. They were succeeding


beyond their wildest anticipations. The table, after various oscillations,
approached the stairway, still carrying the portly investigator. Clinging to
it were a number of enthusiasts who stumbled up the stairway well
toward the top. Suddenly the invisible force weakened, and the table
with its burden, fell with a crash.

The victim was considerably bruised but otherwise physically uninjured.


His vanity had however received a hard jolt and he took no further part
in the séances.

There is significance in the fact that although most people of the rural
districts long ago lost interest in “spirit” phenomena, it has lately
engaged the attention of city dwellers to an increasing extent. Such
investigations passed under the ban of country people because of the
current impression that they were generally demoralizing in their
influence. Those who maintained the churches were skeptical and this
developed antagonisms, which affected attendance upon church and
Sunday school. The “ouija board” is about all there is left of the old
time manifestations in rural New England.

The Story of the Ouija Board


But even the ouija board can carry consternation to the wayward.
A New England youth of unusually good looks became impressed with
the idea that his face could easily be made to be his fortune. The
matrimonial route seemed to be easiest and after a short courtship he
became the husband of a woman of considerable wealth. To be sure
she was quite deaf and some forty years his senior, but there could be
many collateral diversions. His elation was short lived. The old lady had
not lived so many years without acquiring wisdom. She promptly added
to her other bridal accessories a “ouija” with which she soon became
proficient.

Before his marriage the young husband had made the acquaintance of
numerous fair ones of whom chorus girls seemed the most congenial.
But he soon found it wise to avoid their company. With her faithful
ouija, his wife could have him shadowed at all hours of the day. It was
too uncanny. He became the most docile and punctilious of husbands.

Coincidence often assumes an uncanny resemblance to the so-called


supernatural. Instances in which a certain type of dream was followed
by disaster are common to all classes of people. But what is to be said
of “signs” during waking hours? as for example the following legend of
a highly intelligent married couple who would have scorned to palm off
such a narrative unless authentic.

The Unreal Arrival of Uncle Mark


Late one summer evening these middle-aged parents of a considerable
family had just retired to rest, the younger people being long since
abed and asleep. All at once the silence of the farm was broken by the
sound of a horse and buggy coming rapidly up the main road, and
which turned from the highway, passed through the yard and up a
driveway into the horse barn. The farmer and his wife exchanged
glances, one of them remarking that “Uncle Mark,” a brother of the
farmer, was evidently making one of his customary unannounced visits.

Then followed the familiar sounds of the horse being detached from the
buggy and led into the stall. The farmer hastily readjusting his clothing,
took the lamp and went down stairs to admit the visitor. Seeing and
hearing no one he went down the porch and crossed the yard to the
barn. He found no strange horse, wagon or driver.

When the wife was told that what they had both heard so distinctly was
a delusion, she looked very grave.

“That means bad news,” was all she said.

The farmer and his wife went to bed and let us hope they slept the
sleep of the just. The next morning a telegram announced the sudden
death of a near relative. It would be hard to convince any of their
descendants that this fine old couple had betrayed any weak
superstitious delusions in describing this mysterious combination of
happenings.

It is probable that the experienced traveling salesman is about as near


immune to superstitious thrills as any type of citizen, but in one specific
case even his iron nerve gave way.

The Locked Door Which Swung Open


A young man of exceptional vigor and equipoise, traveling through a
hilly country, had occasion to make a late journey across a mountain.
The road was poor and the traveling tedious and he found that he had
sadly miscalculated the time required to complete the trip. He decided
to stop at the first likely looking farmhouse and beg for a chance to stay
over night.

By this time it was very dark but he was able to get a glimpse of two or
three cabins on the way that seemed too utterly unattractive for
consideration. Finally he came to a more commodious looking
establishment and decided to go no further if he could possibly avoid it.
Stopping his horse in front of the house he hallooed several times.
There was no answer, so inferring the inhabitants were sound sleepers,
the young man concluded to first find shelter for his horse and then
come back and in some way or other secure a night’s lodging for
himself.

An outbuilding was located and unharnessing his horse, he tied him to


a beam and after giving the animal some hay and a bedding of the
same, he went back to the farmhouse, intending to pound on the door
until he aroused the inmates. But he did not pound on the door.

As the weary traveler approached the front step, the door began to
turn, swung around slowly and finally stood wide open. There was not
the slightest noise nor sign of any human agency associated with the
door. Every individual hair arose on the young man’s head. He thought
with joy and relief of that good, faithful animal munching his dry hay.
He hastened back to the shed, lay down as near the horse as safety
would permit, and so managed to pass the night.

At daybreak he resumed his journey, but before leaving he observed


positive evidences that the house was uninhabited. The door was
locked!

It is probable that had the salesman had the time and disposition to
make a careful daylight inspection of the vacant house, he might have
discovered some perfectly natural cause for the mysterious actions of
the front door. But his curiosity was not very active just then.

In another instance, the investigations of a traveling salesman nearly


caused a case of sudden death by heart failure.

The Joke Played on the Hotel Porter


This young man found himself marooned for the Sabbath at a little
hotel in a back country town. Sunday afternoon, finding nothing better
to do, he proceeded to put the blasé hotel clerk through a third degree
examination in regard to any local points of interest which might
alleviate the general tiresomeness of the situation. The only interesting
feature apparently possessed by the town was a haunted house
guaranteed to be genuine in every respect.

There was the usual legend of some ghastly tragedy, and the record of
spookish antics, frequently associated with such histories. Altogether
the salesman was disposed to consider this a real find and worth
looking after.

The most conspicuous member of the hotel staff was a colored porter.
Bland and attentive, this young man took his position very seriously
indeed. The salesman became very chummy with the porter. He found
several occasions to utilize his services and showed his appreciation by
liberal tips. It therefore seemed only natural to the porter that the
salesman should propose that he have his company for an evening’s
stroll to look over the town, especially as the suggestion was associated
with the promise of an extra half dollar.

In his conversation with the clerk, the salesman had learned the
general location of the haunted house, and waiting until it was quite
dark he started out in that direction with his escort. He remarked on
the darkness of the night, saying it was just the kind of a night for
ghosts to be on duty. Finally he asked his companion if he knew of any
haunted houses in town. The porter rather reluctantly admitted that he
did know of one and that they were getting pretty near to it.

By this time the porter had evidently lost interest in the excursion and
suggested that he would be needed at the hotel. He was, however,
prevailed upon to go a little further. Shortly afterward, there loomed up
a large old-fashioned dwelling surrounded by considerable grounds
which he pronounced to be the haunted house. It was uninhabited, of
course.

The porter again urged that he would be needed at the hotel, but the
salesman insisted that he must get a little nearer before going back.
When nearly opposite the house, he stopped and took a careful look at
the building which now looked dismal enough in the dim starlight.

The salesman was possessed of a voice that he could make unusually


penetrating. He suddenly gave a tremendous leap backward and yelled
in a most agonizing tone.

“Great Heavens! What is that?”

But his companion did not answer. He disappeared down the road at a
pace that no professional sprinter could excel.

In “the good old days” a ghost seems to have generally appeared to


investigate any unusually spectacular murder. This came about
according to custom following the celebrated pedlar mystery.

The Pedlar Who Disappeared


A German Jew had built up a profitable trade among the farmers in a
certain section and was looked for every summer by his customers. He
traveled with a horse and cart and carried a considerable stock of silks
for dresses and heavy black broadcloth for men’s suits. Another item of
considerable importance in his business was a choice stock of Paisley
shawls.

The prosperous farmer of that period was expected to provide his wife
with at least one black silk dress in addition to the one she may have
had as a part of her wedding outfit, the shawl adding the final touch of
elegance to her wardrobe.

Naturally the wife would expect her husband to be dressed according to


her standard, and that meant at least one new broadcloth suit every
ten or fifteen years. Therefore the pedlar could always count upon a
considerable number of sales and it can be taken for granted that he
made at least a fair profit.

It was, however, often necessary for him to extend credit as actual


money was very scarce in those times. But he knew his customers and
rather encouraged this class of business.

One season the pedlar made his usual rounds, did a considerable credit
business, delivering his goods as usual and—was never seen again.

The farmers who had provided themselves with funds to settle their
accounts could not understand the case. The pedlar was apparently the
last man of their acquaintance to neglect his collections. Time passed,
the year rolled around and nothing was heard. It was indeed a mystery.

One day a marvelous story went the rounds. A well-known young man
announced that he could keep his secret no longer. He had a confession
to make.

He said that about the time of the pedlar’s last visit, returning home
one evening, he had overtaken two men on a lonely road through the
woods, who were carrying a heavy burden wrapped in a blanket.
Finding they were discovered the men had required him, on penalty of
death, to help them bury a man’s body. It was the pedlar.

Pressed for details as to the identity of the probable murderers, he


named two well-known business men of a nearby town who,
presumably, tempted by the large sums of money habitually carried by
the pedlar, had committed the crime.

The accused were naturally placed under arrest, but their denials of the
crime were not vehement as might have been expected, but were
calmly contemptuous. They arranged their affairs as best they could
and settled down to endure confinement in the county jail as patiently
as possible until the next session of court. There does not seem to have
been any evidence to corroborate the testimony of the principal
witness, and when he later appeared before the county prosecutor and
told him the alleged confession was merely a romance suggested to his
mind through a badly distorted sense of humor, there was nothing
further to be done with the alleged murderers except to release them.

While in these latter days such a hoax on the authorities would likely
prove unpleasant to the joker, he apparently escaped any legal penalty.
But he found it expedient to shortly leave the neighborhood, as the
theory was promptly advanced that the original confession was really
justified, but that the witness had in some manner been induced by the
accused parties to retract, probably by a liberal bribe. His later
prosperity in a large New England city was generally attributed to this
source by censorious former neighbors, although others, probably
better informed, were aware that he was a highly paid and valued
employee in a large mercantile establishment.

This would seem to be the logical end of this narrative, but although
the subsequent history of the case can be rather briefly told, what has
been heretofore stated is but the beginning of the story.

Those who had been accused of the crime did not follow the example
of the unreliable witness, but remained to spend the balance of their
days attending to their usual occupations in the town where they had
lived so long. One of these men was considerably older than the other,
and although there had been no special intimacy apparent between the
two from year to year, when the older man eventually developed what
promised to be a fatal illness, the other promptly gave over his business
to a subordinate and took up his abode at the home of the sick man.
Day after day, and in fact night after night, he was always at the
invalid’s call and it was generally and plausibly reported that no one
was left alone with the sick man from that time until his death.
Naturally those who enjoyed the sensational, immediately assumed that
the attendant was afraid to permit his former alleged associate in crime
any opportunity for private conversation with others lest he unburden
his mind by a confession.

Enter the ghost!

During the last years of the man so carefully watched by his partner, he
lived in a large old-fashioned house on a back street, surrounded by
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookluna.com

You might also like