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

Building Java Programs - A Back to Basics Approach Stuart Reges instant download

The document discusses 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, and includes updates such as a new chapter on functional programming with Java 8. The textbook aims to improve student success rates in computer science courses by gradually introducing new syntax and concepts.

Uploaded by

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

Building Java Programs - A Back to Basics Approach Stuart Reges instant download

The document discusses 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, and includes updates such as a new chapter on functional programming with Java 8. The textbook aims to improve student success rates in computer science courses by gradually introducing new syntax and concepts.

Uploaded by

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

Building Java Programs - A Back to Basics

Approach Stuart Reges download

https://textbookfull.com/product/building-java-programs-a-back-
to-basics-approach-stuart-reges-2/

Download more ebook from https://textbookfull.com


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

Building Java Programs - A Back to Basics Approach


Stuart Reges

https://textbookfull.com/product/building-java-programs-a-back-
to-basics-approach-stuart-reges-2/

Building Java Programs: A Back to Basics Approach, 5th


Edition Stuart Reges

https://textbookfull.com/product/building-java-programs-a-back-
to-basics-approach-5th-edition-stuart-reges/

Building Python Programs 1st Edition Stuart Reges

https://textbookfull.com/product/building-python-programs-1st-
edition-stuart-reges/

Simpler Living Back to Basics Guides 2nd Edition Jeff


Davidson

https://textbookfull.com/product/simpler-living-back-to-basics-
guides-2nd-edition-jeff-davidson/
College physics : a strategic approach 4th Edition
Stuart Field

https://textbookfull.com/product/college-physics-a-strategic-
approach-4th-edition-stuart-field/

Artificial Intelligence: A Modern Approach 4th Edition


Stuart Russell

https://textbookfull.com/product/artificial-intelligence-a-
modern-approach-4th-edition-stuart-russell/

RESTful Java Web Services A pragmatic guide to


designing and building RESTful APIs using Java 3rd
Edition Balachandar

https://textbookfull.com/product/restful-java-web-services-a-
pragmatic-guide-to-designing-and-building-restful-apis-using-
java-3rd-edition-balachandar/

A Functional Approach to Java: Augmenting Object-


Oriented Java Code with Functional Principles 1st
Edition Ben Weidig

https://textbookfull.com/product/a-functional-approach-to-java-
augmenting-object-oriented-java-code-with-functional-
principles-1st-edition-ben-weidig/

Back Trouble A New Approach to Prevention and Recovery


based on the Alexander Technique Deborah Caplan

https://textbookfull.com/product/back-trouble-a-new-approach-to-
prevention-and-recovery-based-on-the-alexander-technique-deborah-
caplan/
GLOBAL GLOBAL
EDITION EDITION

For these Global Editions, the editorial team at Pearson has Building Java™ Programs

Building Java™ Programs


collaborated with educators across the world to address a
wide range of subjects and requirements, equipping students A Back to Basics Approach

A Back to Basics Approach


with the best possible learning tools. This Global Edition
preserves the cutting-edge approach and pedagogy of the FOURTH EDITION
original, but also features alterations, customization, and
adaptation from the North American version.
Stuart Reges • Marty Stepp

EDITION
FOURTH
This is a special edition of an established
title widely used by colleges and universities

Stepp
Reges
throughout the world. Pearson published this
exclusive edition for the benefit of students
outside the United States and Canada. If you
purchased this book within the United States

EDITION
GLOBAL
or Canada, you should be aware that it has
been imported without the approval of the
Publisher or Author.

Pearson Global Edition

Reges_04_129216168X_Final.indd 1 08/11/16 5:37 PM


Fourth Edition
Global Edition

Building Java Programs


A Back to Basics Approach

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

A01_REGE1686_04_GE_FM.indd 1 17/11/16 3:27 PM


Vice President, Editorial Director: Marcia Horton Project Manager: Lakeside Editorial Services L.L.C.
Acquisitions Editor: Matt Goldstein Senior Specialist, Program Planning and Support:
Editorial Assistant: Kristy Alaura Maura Zaldivar-Garcia
Acquisitions Editor, Global Editions: Sourabh Maheshwari Senior Manufacturing Controller, Global Editions: Kay
VP of Marketing: Christy Lesko Holman
Director of Field Marketing: Tim Galligan Media Production Manager, Global Editions: Vikram
Product Marketing Manager: Bram Van Kempen Kumar
Field Marketing Manager: Demetrius Hall Cover Design: Lumina Datamatics
Marketing Assistant: Jon Bryant R&P Manager: Rachel Youdelman
Director of Product Management: Erin Gregg R&P Project Manager: Timothy Nicholls
Team Lead, Program and Project Management: Inventory Manager: Meredith Maresca
Scott Disanno Cover Art: © Westend61 Premium/Shutterstock.com
Program Manager: Carole Snyder Full-Service Project Management:
Project Editor, Global Editions: K.K. Neelakantan Apoorva Goel/Cenveo® Publisher Services

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.
Acknowledgements of third-party content appear on pages 1219–1220, 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.
Pearson Education Limited
Edinburgh Gate
Harlow
Essex CM20 2JE
England
and Associated Companies throughout the world
Visit us on the World Wide Web at:
www.pearsonglobaleditions.com
© Pearson Education Limited 2018
The rights of Stuart Reges and Marty Stepp to be identified as the authors of this work have been asserted by them
in accordance with the Copyright, Designs and Patents Act 1988.
Authorized adaptation from the United States edition, entitled Building Java Programs: A Back to Basics Approach,
4th Edition, ISBN 978-0-13-432276-6, by Stuart Reges and Marty Stepp published by Pearson Education © 2017.
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 or otherwise, without either the prior written
permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright
Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS.
All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest
in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply
any affiliation with or endorsement of this book by such owners.
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
10 9 8 7 6 5 4 3 2 1
ISBN 10: 1-292-16168-X
ISBN 13: 978-1-292-16168-6
Typeset in Monotype by Cenveo Publisher Services
Printed and bound in Malaysia.

A01_REGE1686_04_GE_FM.indd 2 14/12/16 6:05 PM


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 stu-
dents 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 program-
ming. 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 manipula-
tion 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 stu-
dents taking an AP/CS A course because of the heavy emphasis on two-dimen-
sional 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

A01_REGE1686_04_GE_FM.indd 3 17/11/16 3:27 PM


4 Preface

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 tradi-
tional 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 chal-
lenge of expressing a large program algorithmically.
• Layered approach. Programming in Java involves many concepts that are dif-
ficult 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 under-
standing 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 program-
ming construct in a rich context that can’t be achieved with short code exam-
ples. 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 com-
puter science, making the book usable for a two-course sequence. Chapters 12–19
explore recursion, searching and sorting, stacks and queues, collection implemen-
tation, linked lists, binary trees, hash tables, heaps, and more. Chapter 12 also

A01_REGE1686_04_GE_FM.indd 4 17/11/16 3:27 PM


Preface 5

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 chap-
ters 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 al-
ready 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:

Programming
Chapter Control Flow Data Techniques Input/Output

1 methods String literals procedural println, print


decomposition
2 definite loops (for) variables, local variables,
expressions, int, class constants,
double pseudocode
3 return values using objects parameters console input, 2D
graphics (optional)
4 conditional char pre/post conditions, printf
(if/else) throwing exceptions
5 indefinite loops boolean assertions,
(while) robust programs
6 Scanner token/line-based file I/O
file 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.

A01_REGE1686_04_GE_FM.indd 5 17/11/16 3:27 PM


6 Preface

The following is a dependency chart for the book:

Chapters 1-6
Programming Fundamentals

Chapter 7 Chapter 8 Chapter 9


Arrays Classes Functional Programming
(except section 19.5)

Chapter 12 Chapter 9
Recursion Inheritance, Chapter 19
Interfaces Section 19.5

Chapter 13
Searching, Chapter 10
Sorting ArrayLists

Chapter 11
Collections

Chapter 14
Chapter 15 Stacks,
Implementing Queues
Collections

Chapter 16
Linked Lists

Chapter 17
Binary Trees

Chapter 18
Hashing,
Heaps

Supplements
Answers to all self-check problems appear on the 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

A01_REGE1686_04_GE_FM.indd 6 17/11/16 3:27 PM


Preface 7

• 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 specifi-
cation 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

The materials are available at www.pearsonglobaleditions.com/reges.

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 program-
ming 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 comprehen-
sive 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
VideoNote
available at the following web site: www.pearsonglobaleditions.com/reges.
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

A01_REGE1686_04_GE_FM.indd 7 06/12/16 11:01 PM


8 Preface

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 spend-
ing 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

A01_REGE1686_04_GE_FM.indd 8 17/11/16 3:27 PM


Preface 9

• 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,

A01_REGE1686_04_GE_FM.indd 9 17/11/16 3:27 PM


10 Preface

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 assis-
tant 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

Acknowledgments for the Global Edition


Pearson would like to thank and acknowledge the following people for their contribu-
tions to the Global Edition.

Contributor
Ankur Saxena, Amity University

Reviewers
Arup Bhattacharya, RCC Institute of Technology
Soumen Mukherjee, RCC Institute of Technology
Khyat Sharma

A01_REGE1686_04_GE_FM.indd 10 14/12/16 5:16 PM


A01_REGE1686_04_GE_FM.indd 11 12/12/16 5:31 pm
LOCATION OF VIDEO NOTES IN THE TEXT
www.pearsonglobaleditions.com/reges VideoNote

Chapter 1 Pages 57, 66


Chapter 2 Pages 91, 100, 115, 123, 136
Chapter 3 Pages 167, 182, 187, 193
Chapter 3G Pages 223, 241
Chapter 4 Pages 269, 277, 304
Chapter 5 Pages 350, 353, 355, 359, 382
Chapter 6 Pages 422, 435, 449
Chapter 7 Pages 484, 491, 510, 531
Chapter 8 Pages 561, 573, 581, 594
Chapter 9 Pages 623, 636, 652
Chapter 10 Pages 698, 703, 712
Chapter 11 Pages 742, 755, 763
Chapter 12 Pages 790, 798, 835
Chapter 13 Pages 860, 863, 869
Chapter 14 Pages 915, 922
Chapter 15 Pages 956, 962, 966
Chapter 16 Pages 998, 1005, 1018
Chapter 17 Pages 1063, 1064, 1074
Chapter 18 Pages 1099, 1118

12

A01_REGE1686_04_GE_FM.indd 12 17/11/16 3:27 PM


Brief Contents

Chapter 1 Introduction to Java Programming 27


Chapter 2 Primitive Data and Definite Loops 89
Chapter 3 Introduction to Parameters and Objects 163
Supplement 3G Graphics (Optional) 222
Chapter 4 Conditional Execution 264
Chapter 5 Program Logic and Indefinite Loops 341
Chapter 6 File Processing 413
Chapter 7 Arrays469
Chapter 8 Classes556
Chapter 9 Inheritance and Interfaces 613
Chapter 10 ArrayLists688
Chapter 11 Java Collections Framework 741
Chapter 12 Recursion780
Chapter 13 Searching and Sorting 858
Chapter 14 Stacks and Queues 910
Chapter 15 Implementing a Collection Class 948
Chapter 16 Linked Lists 991
Chapter 17 Binary Trees 1043
Chapter 18 Advanced Data Structures 1097
Chapter 19 Functional Programming with Java 8 1133
Appendix A Java Summary 1175
Appendix B The Java API Specification and Javadoc Comments 1190
Appendix C Additional Java Syntax 1196

13

A01_REGE1686_04_GE_FM.indd 13 14/12/16 5:17 PM


This page intentionally left blank

561590_MILL_MICRO_FM_ppi-xxvi.indd 2 24/11/14 5:26 PM


Contents

Chapter 1 Introduction to Java Programming 27


1.1 Basic Computing Concepts 28
Why Programming? 28
Hardware and Software 29
The Digital Realm 30
The Process of Programming 32
Why Java? 33
The Java Programming Environment 34
1.2 And Now—Java 36
String Literals (Strings) 40
System.out.println 41
Escape Sequences 41
print versus println 43
Identifiers and Keywords 44
A Complex Example: DrawFigures1 46
Comments and Readability 47
1.3 Program Errors 50
Syntax Errors 50
Logic Errors (Bugs) 54
1.4 Procedural Decomposition 54
Static Methods 57
Flow of Control 60
Methods That Call Other Methods 62
An Example Runtime Error 65
1.5 Case Study: DrawFigures 66
Structured Version 67
Final Version without Redundancy 69
Analysis of Flow of Execution 70

Chapter 2 Primitive Data and Definite Loops 89


2.1 Basic Data Concepts 90
Primitive Types 90
15

A01_REGE1686_04_GE_FM.indd 15 17/11/16 3:27 PM


16 Contents

Expressions 91
Literals 93
Arithmetic Operators 94
Precedence 96
Mixing Types and Casting 99
2.2 Variables 100
Assignment/Declaration Variations 105
String Concatenation 108
Increment/Decrement Operators 110
Variables and Mixing Types 113
2.3 The for Loop 115
Tracing for Loops 117
for Loop Patterns 121
Nested for Loops 123
2.4 Managing Complexity 125
Scope 125
Pseudocode 131
Class Constants 134
2.5 Case Study: Hourglass Figure 136
Problem Decomposition and Pseudocode 137
Initial Structured Version 139
Adding a Class Constant 140
Further Variations 143

Chapter 3 Introduction to Parameters


and Objects 163
3.1 Parameters 164
The Mechanics of Parameters 167
Limitations of Parameters 171
Multiple Parameters 174
Parameters versus Constants 177
Overloading of Methods 177
3.2 Methods That Return Values 178
The Math Class 179
Defining Methods That Return Values 182
3.3 Using Objects 186
String Objects 187
Interactive Programs and Scanner Objects 193
Sample Interactive Program 196

A01_REGE1686_04_GE_FM.indd 16 17/11/16 3:27 PM


Contents 17

3.4 Case Study: Projectile Trajectory 199


Unstructured Solution 203
Structured Solution 205

Supplement 3G Graphics (Optional) 222


3G.1 Introduction to Graphics 223
DrawingPanel 223
Drawing Lines and Shapes 224
Colors 229
Drawing with Loops 232
Text and Fonts 236
Images 239
3G.2 Procedural Decomposition with Graphics 241
A Larger Example: DrawDiamonds 242
3G.3 Case Study: Pyramids 245
Unstructured Partial Solution 246
Generalizing the Drawing of Pyramids 248
Complete Structured Solution 249

Chapter 4 Conditional Execution 264


4.1 if/else Statements 265
Relational Operators 267
Nested if/else Statements 269
Object Equality 276
Factoring if/else Statements 277
Testing Multiple Conditions 279
4.2 Cumulative Algorithms 280
Cumulative Sum 280
Min/Max Loops 282
Cumulative Sum with if 286
Roundoff Errors 288
4.3 Text Processing 291
The char Type 291
char versus int 292
Cumulative Text Algorithms 293
System.out.printf 295

4.4 Methods with Conditional Execution 300


Preconditions and Postconditions 300
Throwing Exceptions 300

A01_REGE1686_04_GE_FM.indd 17 17/11/16 3:27 PM


18 Contents

Revisiting Return Values 304


Reasoning about Paths 309

4.5 Case Study: Body Mass Index 311


One-Person Unstructured Solution 312
Two-Person Unstructured Solution 315
Two-Person Structured Solution 317
Procedural Design Heuristics 321

Chapter 5 Program Logic and Indefinite Loops 341


5.1 The while Loop 342
A Loop to Find the Smallest Divisor 343
Random Numbers 346
Simulations 350
do/while Loop 351

5.2 Fencepost Algorithms 353


Sentinel Loops 355
Fencepost with if 356

5.3 The boolean Type 359


Logical Operators 361
Short-Circuited Evaluation 364
boolean Variables and Flags 368
Boolean Zen 370
Negating Boolean Expressions 373

5.4 User Errors 374


Scanner Lookahead 375
Handling User Errors 377

5.5 Assertions and Program Logic 379


Reasoning about Assertions 381
A Detailed Assertions Example 382

5.6 Case Study: NumberGuess 387


Initial Version without Hinting 387
Randomized Version with Hinting 389
Final Robust Version 393

Chapter 6 File Processing 413


6.1 File-Reading Basics 414
Data, Data Everywhere 414

A01_REGE1686_04_GE_FM.indd 18 17/11/16 3:27 PM


Contents 19

Files and File Objects 414


Reading a File with a Scanner 417
6.2 Details of Token-Based Processing 422
Structure of Files and Consuming Input 424
Scanner Parameters 429
Paths and Directories 430
A More Complex Input File 433
6.3 Line-Based Processing 435
String Scanners and Line/Token Combinations 436
6.4 Advanced File Processing 441
Output Files with PrintStream 441
Guaranteeing That Files Can Be Read 446
6.5 Case Study: Zip Code Lookup 449

Chapter 7 Arrays 469


7.1 Array Basics 470
Constructing and Traversing an Array 470
Accessing an Array 474
A Complete Array Program 477
Random Access 481
Arrays and Methods 484
The For-Each Loop 487
Initializing Arrays 489
The Arrays Class 490
7.2 Array-Traversal Algorithms 491
Printing an Array 492
Searching and Replacing 494
Testing for Equality 497
Reversing an Array 498
String Traversal Algorithms 503
Functional Approach 504
7.3 Reference Semantics 505
Multiple Objects 507
7.4 Advanced Array Techniques 510
Shifting Values in an Array 510
Arrays of Objects 514
Command-Line Arguments 516
Nested Loop Algorithms 516

A01_REGE1686_04_GE_FM.indd 19 17/11/16 3:27 PM


20 Contents

7.5 Multidimensional Arrays 518


Rectangular Two-Dimensional Arrays 518
Jagged Arrays 520

7.6 Arrays of Pixels 525

7.7 Case Study: Benford’s Law 530


Tallying Values 531
Completing the Program 535

Chapter 8 Classes 556


8.1 Object-Oriented Programming 557
Classes and Objects 558
Point Objects 560

8.2 Object State and Behavior 561


Object State: Fields 562
Object Behavior: Methods 564
The Implicit Parameter 567
Mutators and Accessors 569
The toString Method 571

8.3 Object Initialization: Constructors 573


The Keyword this 578
Multiple Constructors 580

8.4 Encapsulation  581


Private Fields 582
Class Invariants 588
Changing Internal Implementations 592

8.5 Case Study: Designing a Stock Class 594


Object-Oriented Design Heuristics 595
Stock Fields and Method Headers 597
Stock Method and Constructor Implementation 599

Chapter 9 Inheritance and Interfaces 613


9.1 Inheritance Basics 614
Nonprogramming Hierarchies 615
Extending a Class 617
Overriding Methods 621

A01_REGE1686_04_GE_FM.indd 20 17/11/16 3:27 PM


Contents 21

9.2 Interacting with the Superclass 623


Calling Overridden Methods 623
Accessing Inherited Fields 624
Calling a Superclass’s Constructor 626
DividendStock Behavior 628
The Object Class 630
The equals Method 631
The instanceof Keyword 634
9.3 Polymorphism 636
Polymorphism Mechanics 639
Interpreting Inheritance Code 641
Interpreting Complex Calls 643
9.4 Inheritance and Design 646
A Misuse of Inheritance 646
Is-a Versus Has-a Relationships 649
Graphics2D 650
9.5 Interfaces 652
An Interface for Shapes 653
Implementing an Interface 655
Benefits of Interfaces 658
9.6 Case Study: Financial Class Hierarchy 660
Designing the Classes 661
Redundant Implementation 665
Abstract Classes 668

Chapter 10 ArrayLists 688


10.1 ArrayLists 689
Basic ArrayList Operations 690
ArrayList Searching Methods 693
A Complete ArrayList Program 696
Adding to and Removing from an ArrayList 698
Using the For-Each Loop with ArrayLists 702
Wrapper Classes 703
10.2 The Comparable Interface 706
Natural Ordering and compareTo 708
Implementing the Comparable Interface 712
10.3 Case Study: Vocabulary Comparison 718
Some Efficiency Considerations 718
Version 1: Compute Vocabulary 721

A01_REGE1686_04_GE_FM.indd 21 17/11/16 3:27 PM


22 Contents

Version 2: Compute Overlap 724


Version 3: Complete Program 729

Chapter 11 Java Collections Framework 741


11.1 Lists 742
Collections 742
LinkedList versus ArrayList 743
Iterators 746
Abstract Data Types (ADTs) 750
LinkedList Case Study: Sieve 752

11.2 Sets 755


Set Concepts 756
TreeSet versus HashSet 758
Set Operations 759
Set Case Study: Lottery 761

11.3 Maps 763


Basic Map Operations 764
Map Views (keySet and values) 766
TreeMap versus HashMap 767
Map Case Study: WordCount 768
Collection Overview 771

Chapter 12 Recursion 780


12.1 Thinking Recursively 781
A Nonprogramming Example 781
An Iterative Solution Converted to Recursion 784
Structure of Recursive Solutions 786

12.2 A Better Example of Recursion 788


Mechanics of Recursion 790

12.3 Recursive Functions and Data 798


Integer Exponentiation 798
Greatest Common Divisor 801
Directory Crawler 807
Helper Methods 811

12.4 Recursive Graphics 814

A01_REGE1686_04_GE_FM.indd 22 17/11/16 3:27 PM


Contents 23

12.5 Recursive Backtracking 818


A Simple Example: Traveling North/East 819
8 Queens Puzzle 824
Solving Sudoku Puzzles 831

12.6 Case Study: Prefix Evaluator 835


Infix, Prefix, and Postfix Notation 835
Evaluating Prefix Expressions 836
Complete Program 839

Chapter 13 Searching and Sorting 858


13.1 Searching and Sorting in the Java Class Libraries 859
Binary Search 860
Sorting 863
Shuffling 864
Custom Ordering with Comparators 865
13.2 Program Complexity 869
Empirical Analysis 870
Complexity Classes 876
13.3 Implementing Searching and Sorting Algorithms 878
Sequential Search 879
Binary Search 880
Recursive Binary Search 883
Searching Objects 886
Selection Sort 877
13.4 Case Study: Implementing Merge Sort 890
Splitting and Merging Arrays 891
Recursive Merge Sort 894
Complete Program 897

Chapter 14 Stacks and Queues 910


14.1 Stack/Queue Basics 911
Stack Concepts 911
Queue Concepts 914
14.2 Common Stack/Queue Operations 915
Transferring Between Stacks and Queues 917
Sum of a Queue 918
Sum of a Stack 919

A01_REGE1686_04_GE_FM.indd 23 17/11/16 3:27 PM


24 Contents

14.3 Complex Stack/Queue Operations 922


Removing Values from a Queue 922
Comparing Two Stacks for Similarity 924
14.4 Case Study: Expression Evaluator 926
Splitting into Tokens 927
The Evaluator 932

Chapter 15 Implementing a Collection Class 948


15.1 Simple ArrayIntList 949
Adding and Printing 949
Thinking about Encapsulation 955
Dealing with the Middle of the List 956
Another Constructor and a Constant 961
Preconditions and Postconditions 962
15.2 A More Complete ArrayIntList 966
Throwing Exceptions 966
Convenience Methods 969
15.3 Advanced Features 972
Resizing When Necessary 972
Adding an Iterator 974
15.4 ArrayList<E> 980

Chapter 16 Linked Lists 991


16.1 Working with Nodes 992
Constructing a List 993
List Basics 995
Manipulating Nodes 998
Traversing a List 1001
16.2 A Linked List Class 1005
Simple LinkedIntList 1005
Appending add 1007
The Middle of the List 1011
16.3 A Complex List Operation 1018
Inchworm Approach 1023
16.4 An IntList Interface 1024

A01_REGE1686_04_GE_FM.indd 24 17/11/16 3:27 PM


Contents 25

16.5 LinkedList<E> 1027


Linked List Variations 1028
Linked List Iterators 1031
Other Code Details 1033

Chapter 17 Binary Trees 1043


17.1 Binary Tree Basics 1044
Node and Tree Classes 1047

17.2 Tree Traversals 1048


Constructing and Viewing a Tree 1054

17.3 Common Tree Operations 1063


Sum of a Tree 1063
Counting Levels 1064
Counting Leaves 1066

17.4 Binary Search Trees 1067


The Binary Search Tree Property 1068
Building a Binary Search Tree 1070
The Pattern x = change(x) 1074
Searching the Tree 1077
Binary Search Tree Complexity 1081

17.5 SearchTree<E> 1082

Chapter 18 Advanced Data Structures 1097

18.1 Hashing 1098


Array Set Implementations 1098
Hash Functions and Hash Tables 1099
Collisions 1101
Rehashing 1106
Hashing Non-Integer Data 1109
Hash Map Implementation 1112

18.2 Priority Queues and Heaps 1113


Priority Queues 1113
Introduction to Heaps 1115
Removing from a Heap 1117
Adding to a Heap 1118
Array Heap Implementation 1120
Heap Sort 1124

A01_REGE1686_04_GE_FM.indd 25 17/11/16 3:27 PM


26 Contents

Chapter 19 Functional Programming


with Java 8 1133
19.1 Effect-Free Programming 1134

19.2 First-Class Functions 1137


Lambda Expressions 1140

19.3 Streams 1143


Basic Idea 1143
Using Map 1145
Using Filter 1146
Using Reduce 1148
Optional Results 1149

19.4 Function Closures 1150

19.5 Higher-Order Operations on Collections 1153


Working with Arrays 1154
Working with Lists 1155
Working with Files 1159

19.6 Case Study: Perfect Numbers 1160


Computing Sums 1161
Incorporating Square Root 1164
Just Five and Leveraging Concurrency 1167

Appendix A Java Summary 1175


Appendix B The Java API Specification
and Javadoc Comments 1190
Appendix C Additional Java Syntax 1196
Index1205
Credits1219

A01_REGE1686_04_GE_FM.indd 26 17/11/16 3:27 PM


Chapter 1
Introduction to
Java Programming

Introduction
1.1 Basic Computing Concepts
■ Why Programming?
This chapter begins with a review of some basic terminology about com- ■ Hardware and Software
puters and computer programming. Many of these concepts will come up ■ The Digital Realm
in later chapters, so it will be useful to review them before we start delving
■ The Process of Programming
■ Why Java?
into the details of how to program in Java. ■ The Java Programming
Environment
We will begin our exploration of Java by looking at simple programs that
1.2 And Now—Java
produce output. This discussion will allow us to explore many elements
■ String Literals (Strings)
that are common to all Java programs, while working with programs that ■ System.out.println
are fairly simple in structure. ■ Escape Sequences
■ print versus println
After we have reviewed the basic elements of Java programs, we will ■ Identifiers and Keywords
explore the technique of procedural decomposition by learning how to
■ A Complex Example:
DrawFigures1
break up a Java program into several methods. Using this technique, we ■ Comments and Readability
can break up complex tasks into smaller subtasks that are easier to manage
1.3 Program Errors
and we can avoid redundancy in our program solutions. ■ Syntax Errors
■ Logic Errors (Bugs)

1.4 Procedural Decomposition


■ Static Methods
■ Flow of Control
■ Methods That Call Other
Methods
■ An Example Runtime Error

1.5 Case Study: DrawFigures


■ Structured Version
■ Final Version without
Redundancy
■ Analysis of Flow of Execution

27

M01_REGE1686_04_GE_C01.indd 27 04/11/16 2:34 PM


28 Chapter 1 Introduction to Java Programming

1.1 Basic Computing Concepts


Computers are pervasive in our daily lives, and, thanks to the Internet, they give us
access to nearly limitless information. Some of this information is essential news,
like the headlines at cnn.com. Computers let us share photos with our families and
map directions to the nearest pizza place for dinner.
Lots of real-world problems are being solved by computers, some of which don’t
much resemble the one on your desk or lap. Computers allow us to sequence the
human genome and search for DNA patterns within it. Computers in recently manu-
factured cars monitor each vehicle’s status and motion. Digital music players such as
Apple’s iPod actually have computers inside their small casings. Even the Roomba
vacuum-cleaning robot houses a computer with complex instructions about how to
dodge furniture while cleaning your floors.
But what makes a computer a computer? Is a calculator a computer? Is a human
being with a paper and pencil a computer? The next several sections attempt to
address this question while introducing some basic terminology that will help prepare
you to study programming.

Why Programming?
At most universities, the first course in computer science is a programming course.
Many computer scientists are bothered by this because it leaves people with the
impression that computer science is programming. While it is true that many trained
computer scientists spend time programming, there is a lot more to the discipline. So
why do we study programming first?
A Stanford computer scientist named Don Knuth answers this question by saying
that the common thread for most computer scientists is that we all in some way work
with algorithms.

Algorithm
A step-by-step description of how to accomplish a task.

Knuth is an expert in algorithms, so he is naturally biased toward thinking of them


as the center of computer science. Still, he claims that what is most important is not
the algorithms themselves, but rather the thought process that computer scientists
employ to develop them. According to Knuth,

It has often been said that a person does not really understand something
until after teaching it to someone else. Actually a person does not really
understand something until after teaching it to a computer, i.e., expressing
it as an algorithm.1

1Knuth, Don. Selected Papers on Computer Science. Stanford, CA: Center for the Study of Language and
Information, 1996.

M01_REGE1686_04_GE_C01.indd 28 04/11/16 2:34 PM


Another Random Document on
Scribd Without Any Related Topics
The Project Gutenberg eBook of The World's
Best Poetry, Volume 09: Of Tragedy: of
Humour
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 World's Best Poetry, Volume 09: Of Tragedy: of Humour

Editor: Bliss Carman

Contributor: Francis Barton Gummere

Release date: July 15, 2013 [eBook #43223]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Charles Aldarondo, Paul Marshall and the Online


Distributed Proofreading Team at http://www.pgdp.net

*** START OF THE PROJECT GUTENBERG EBOOK THE WORLD'S


BEST POETRY, VOLUME 09: OF TRAGEDY: OF HUMOUR ***
VI Fancy:
I Home: Friendship
Sentiment
VII Descriptive:
II Love
Narrative
III Sorrow and VIII National
Consolation Spirit
IV The Higher
IX Tragedy: Humor
Life
X Poetical
V Nature
Quotations

THE WORLD'S
BEST POETRY
IN TEN VOLUMES, ILLUSTRATED

Editor-in-Chief
BLISS CARMAN

Associate Editors
John Vance Cheney Charles G. D. Roberts
Charles F. Richardson Francis H. Stoddard

Managing Editor
John R. Howard

JOHN D. MORRIS AND COMPANY


PHILADELPHIA
Copyright, 1904, by
John D. Morris & Company
JOHANN WOLFGANG von GOETHE.
Photogravure after portrait by Stieler.
The World's Best Poetry Vol. IX
Of TRAGEDY:
of HUMOR

THE OLD CASE OF


POETRY
IN A NEW COURT

By FRANCIS A. GUMMERE

JOHN D. MORRIS AND COMPANY


PHILADELPHIA
Copyright, 1904, by
John D. Morris & Company
NOTICE OF COPYRIGHTS.
——
I.

American poems in this volume within the legal protection of


copyright are used by the courteous permission of the owners,—
either the publishers named in the following list or the authors or
their representatives in the subsequent one,—who reserve all their
rights. So far as practicable, permission has been secured, also for
poems out of copyright.

Publishers of THE WORLD'S BEST POETRY.


1904.
The Bobbs-Merrill Company, Indianapolis.—F. L. Stanton:
"Plantation Ditty."
The Century Co., New York.—I. Russell: "De Fust
Banjo," "Nebuchadnezzar."
Messrs. Harper & Brothers, New York.—W. A. Butler:
"Nothing to Wear;" Will Carleton: "The New Church
Organ."
Messrs. Houghton, Mifflin & Co., Boston.—W. H.
Brownell: "Lawyer's Invocation to Spring;" J. T. Fields:
"The Nantucket Skipper;" Bret Harte: "Dow's Flat,"
"Jim," "Plain Language from Truthful James," "To the
Pliocene Skull," "Ramon," "The Society upon the
Stanislaus;" J. Hay: "Banty Tim," "Jim Bludso," "Little
Breeches;" O. W. Holmes: "Ode for a Social Meeting,"
"One-Horse Shay," "Rudolph the Headsman;" H. W.
Longfellow: "The Wreck of the Hesperus;" J. R. Lowell:
"America," "The Grave-Yard," "What Mr. Robinson
Thinks;" J. J. Roche: "The V-A-S-E;" C. Scollard:
"Khamsin."
The J. B. Lippincott Company, Philadelphia.—G. H. Boker:
"Countess Laura."
Mr. David MacKay, Philadelphia.—C. G. Leland: "Hans
Breitmann's Party," "Ritter Hugo."
Messrs. Charles Scribner's Sons, New York.—R. Bridges
(Droch): "For a Novel of Hall Caine's."
Messrs. Small, Maynard & Co., Boston.—Charlotte
Perkins Gilman: "A Conservative."

II.

American poems in this volume by the authors whose names are


given below are the copyrighted property of the authors, or of their
representatives named in parenthesis, and may not be reprinted
without their permission, which for the present work has been
courteously granted.

Publishers of THE WORLD'S BEST POETRY.


1904.
C. F. Adams; C. T. Brooks (Mrs. Harriet Lyman Brooks);
F. G. Burgess; R. W. Chambers; N. H. Dole; S. W. Foss;
I. Wallace; J. W. Riley.

THE OLD CASE OF POETRY


IN A NEW COURT.

BY FRANCIS BARTON GUMMERE.


Although hailed as queen of the arts and hedged about by a kind
of divinity, Poetry seems to sit on an always tottering throne. In
nearly every age known to human records, some one has chronicled
his forebodings that the days of Poetry were numbered; and again
the critic, or the Poet himself, has plucked up his courage and uttered
a fairly hopeful defence. Yet even this hope has been absent from
periods which now seem poetic in the highest degree. Michael
Drayton could find scant consolation for his art, dedicating certain
poems to gentlemen who "in these declining times.... love and
cherish neglected poesy." The enemies of poetry are always alert,
and often come disguised as friends. When, at the end of the Middle
Ages, moralists ceased to attack the poets, there appeared the man
of science, a far more formidable person; and, under cover of the
dust and smoke in strong battle waged between these open foes,
poetry has been spoiled of one cherished possession after another at
the hands of a professedly ardent ally. Horace Walpole's alternative
neatly implied the whole question under debate: "Poetry," he
complained, "is gone to bed, or into our prose,"—an odd speech for
one who helped to ring the romantic rising-bell. Bulwer, writing
ponderously "On Certain Principles of Art in Works of the
Imagination," was sure that Prose had come to be the only medium
of artistic narrative. Malicious people point even now to a language
which never had any prose, and yet has lost its splendid heritage of
verse: barring Grillparzer, silent long before his death, Germany has
not seen a poet for the last fifty years. But, answers the optimist,
who knows what ambulando argument for poetry is not now
preparing somewhere in the fatherland? And as for Bulwer, his ink
was hardly dry when Tennyson began those charming and miscalled
Idylls of the King. If epic poetry seems dead just now, it seemed
quite as dead four hundred years ago in France. So this harmless war
is waged. What comes of it all? What has been done? What progress?
Other causes come up, find a hearing on the evidence, get a verdict
more or less in agreement with facts, and go upon record; this case
lies hopeless in chancery. Why must it wait there, along with all the
old metaphysical questions, for a decision that never can be handed
down? If one may do nothing else, one may at least take the case to
a different court, demand fresh evidence, and appeal to another code
of laws.
Before all things, it behooves both parties to this argument to
come at the facts in the case.
Barring a threat or so of historical treatment, as in Macaulay's
famous essay on Milton, writers who handle this matter of the decline
of poetry invariably pass either into critical discussion of more or less
value in itself, or else into amiable hysterics. To speak brutal truth,
hysterics are preferred, and little else is recognized. It is all very well
to say that the study of poetry has been put on a scientific basis; the
mass of readers who are interested in poetry, the mass of reviewers,
—and one finds this true in quite unexpected quarters,—care for no
scientific basis at all. In other words, they exclude from their study of
poetry a good half of the facts of poetry.
In any living science one begins by finding and grouping all the
facts, high and low alike; and one then proceeds to establish the
relations of these facts on lines of record and comparison. The facts
of poetry should be conterminous with the whole range of poetic
material; and when one faces this material, one has to do with an
element in human life, although the ordinary writer seems to think
that he degrades his subject by taking such an attitude. He searches
for the cause and fact of poetry in a sphere outside of human life,
removed from ordinary human conditions, and touching only an
infinitesimal part of the sum of poetic material. True, there is nothing
nobler than the effort to reckon with great poetry, and competent
critics who succeed in this must always hold a conspicuous place in
letters; but great poetry and the great critic are not all. Poetry, high
or low, as product of a human impulse and as a constant element in
the life of man, belongs to that history which has been defined of late
as "concrete sociology"—the study of human society itself; and it is
on this ground, and not in criticism, that the question of the decline
of poetry must be asked and answered.
The task of poetics, as yet almost untried, is to make clear the
relations between higher and lower forms. Like war, marriage,
worship, magic, personal adornment, and a dozen other institutions
of this sort, poetry is an element in human life which seems to go
back to the beginnings of society. Trustworthy writers even say it was
one of the more conspicuous factors in the making of society; and
when one is asked whether poetry, that is, emotional rhythmic
utterances, must be regarded as a decreasing factor in contemporary
social progress, one faces a question of sociological as well as of
literary interest, and one must answer it on broader ground than
biographical criticism, in clearer terms than can be furnished by those
old hysterics about genius. To treat the question as it is almost
invariably treated, to make it an ingenious speculation whether any
more great poets can arise under our modern conditions, whether
Goethe, if he were born now, would not be simply a great naturalist,
and whether Robert Browning or Huxley better solved the riddle of
the painful earth,—all this is to keep up an unwholesome separation
of poetics from vital and moving sciences, and to make the discussion
itself mere chatter.
The advantage in this sociological study of poetry is that it can
keep abreast of other sciences. The oars dip into actual water, the
boat moves, whether with the current of opinion or against it, and
the landscape changes for one's pains; anything is better than the old
rowing-machines, or rather than the theatrical imitation of a boat,
with the sliding scenery and the spectators that pay to be fooled.
Moreover, it is wide scientific work, not laboratory methods, so called,
like countings of words, curves of expression, and all such pleasant
devices that rarely mount above the mechanical in method and the
wholly external in results; in sociological poetics one is dealing with
the life of the race and with the heart of man. F. Schlegel's famous
word about art in general holds firm here; the science of poetry is the
history of poetry, history in its widest and deepest sense. The futile
character of poetic studies springs from that fatal ease with which a
powerful thinker sets down thoughts about poetry, and from the
reluctance to under-take such hard work as confronts even our
powerful thinker when he is minded to know the facts. To get the
wide outlook, one must climb; to get the deep insight, one must
analyze and order and compare. Now the pity of it is that this outlook
and this insight, this appreciation of a masterpiece and this
knowledge of the vast material of which it is part, are not only rarely
achieved in themselves, but are seldom if ever united. The great
poems are studied apart; and as a group, more or less stable, they
form what is known as poetry. Detached from the mass of verse, and
so from the social medium where all poetry begins and grows, they
are referred to those conditions of genius which can tell at best but
half the tale; while that very mass of verse which one concedes to
the social group, that unregarded rhythmic utterance of field and
festival in which communal emotion—the agitating joys and sorrows
of the common people—found and still finds vent, is left as a fad of
ethnologists and folk-lore societies. But the material thus divided
belongs together; each half should explain the other half; and such
an unscientific rejection of material must take poetics hopelessly out
of the running.
This plea for a more comprehensive range of material holds good
not only in the discussion of poetry in general, its origins, history,
future, but in the study of the great poem itself. Take something that
every one reads, and even Macaulay's schoolboy studies—the Lycidas
of Milton. Reader, critic, biographer, have long since come to terms
with the poem; it stirs heart and mind, it belongs to the
masterpieces, it voices the genius of Milton, it echoes Puritan
England. Here one usually stops; but here one should not stop.
Lycidas, as a poem, is the outcome of human emotion in long
reaches of social progress; it is primarily a poem of grief for the dead,
a link in that chain of evolution in rhythmic utterance which leads
from wild gestures and inarticulate cries up to the stately march of
Milton's verse and the higher mood of his thought. So far from
degrading one's conception of great poetry, the comparison of rough
communal verse should throw into strongest relief the dignity and the
majesty of a poet's art. One has taken this poet from his parochial
limits, and set him strongly lighted, at the front of a great stage, with
its dim background full of half-seen, strangely moving figures; his
song is now detached from a vast chorus of human lamentation, and
now sinks back into it as into its source. In certain great elegies, as
also in the hymeneal, this chorus actually lingers as a refrain. True,
the individuals of the chorus are seldom interesting in themselves.
The black fellow of Australia shall not soothe our grief with his
howlings for his dead, nor even the Corsican widow with her vocero.
But the chorus as chorus is impressive enough; it is a part of the
piece; heard or unheard, it belongs with the triumphs of individual
art. Somewhere in every great poem lurks this legacy of communal
song. It may better be called the silent partner, without whose
capital, at the least, no poet can now trade in Parnassian ware; and
as for lyric verse, there the partner is not even silent. All amorous
lyric, whether of German Walther or of Roman Catullus, holds an
echo of festal throngs singing and dancing at the May. The
troubadours come down to us with proud names, yet they are only
spokesmen of an aristocratic guild; and this again was but a sifting
and a refinement of the throngs which danced about their regine
Avrillouse a thousand years ago. It was once lad and lass in the
crowd; it comes to be lover and high-born dame at daybreak, with a
warning from the watcher on the castle walls; then that vogue
passes, with all its songs that seem to sing themselves; the situation
has grown deplorably unconventional, and the note is false. Amorous
lyric waxes mere grave, taking on a new privacy of utterance, and a
new individuality of tone. It is now the subtle turn of thought, and
not the cadence of festal passion, which sets off Lovelace's one
perfect song from all its kind; yet, without that throb of passion, that
rhythm as of harmonious steps, one of them a piece of human
nature, and the other a legacy from the throng, Lovelace had never
made his verses and there would be no lyric in the world.
Poetry is thus a genesis in the throng, then an exodus with the
solitary poet, then—though this is too often forgotten—a return to
the throng. At least it is so with the great poets. Not the poet, but
the verse-smith, the poetaster, is anxious to deny his parentage in
communal song, and to set for his excellent differences. He will daze
the editor and force his way into the magazine by tricks of
expression, a new adjective, a shock of strange collocations. In a
steamboat on the Baltic I once met a confidential soul who told me of
his baffled designs upon the vogue of modern fiction. He had written,
it seemed, a novel without a woman in it; and he had printed this
novel in red ink. "And I am not famous yet," he sighed. So with one
kind of minor poet. He works through eccentricities and red ink. He is
like Jean Paul's army chaplain Schmelzle, who, when a boy in church,
was so often tempted to rise and cry aloud, "Here am I, too, Mr.
Parson!" It is not so with the great poets, not so even with those
poets whom one may not call great, but who know how to touch the
popular heart. All the masters, Homer, Shakespeare, Goethe, even
Dante, win their greatest triumphs by coming back to simplicity in
form and diction as to the source of all poetic expression. Or, to put it
more scientifically, in any masterpiece one will find the union of
individual genius with that harmony of voices and sympathy of hearts
achieved by long ages of poetic evolution working in the social mass.
If such a range of poetic material is needed even in criticism, how
strictly must it be demanded in any question about the art as a
whole! One may turn from history to prophecy; but poetry must still
be studied even more rigidly in its full range and with regard to all
human elements in the case. Because the communal elements, once
so plain and insistent, now elude all but the most searching gaze,
that is no reason for leaving them out of the account. Hennequin saw
that simply for critical purposes one must reckon not only with the
maker of poetry, but with the consumer as well; and the student of
poetry at large must go still farther. It is after all only a remnant who
choose and enjoy great poetry, just as it is only a remnant who follow
righteousness in private life and probity in civic standards.
But what of the cakes and ale? What of the uncritical folk? What
stands now, since people have come indoors, for the old ring of
dancers, the old songs of May and Harvest Home? Does the lapse of
these mean a lapse in poetry at large? Or what has taken their place?
How shall one dispose of the room over a village store, the hot stove,
the folk in Sunday dress, and the young woman who draws tears
down the very grocer's cheek as she "renders" Curfew Shall Not Ring
To-Night? What of the never-ending crop of songs in street and
concert-hall, and on the football field, verses that still time the
movements of labor and the steps of a marching crowd? What of
homely, comfortable poetry, too, commonplace perhaps, but dear to
declaiming youth? Only a staff cut from Sophoclean timber will
support your lonely dreamer as he makes his way over the marl; but
the common citizen, who does most of the world's work, and who
has more to do with the future of poetry than a critic will concede,
finds his account in certain smooth, didactic, and mainly cheerful
verses which appear in the syndicate newspapers, and will never
attain a magazine or an anthology. If singing throngs keep rhythm
alive, it is this sort of poets that must both make and mend the paths
of genius. Commonplace is a poor word. Horace gives one nothing
else; but a legion of critics shall not keep us from Horace, and even
Matthew Arnold, critic as he was, fell back for his favorite poem on
that seventh ode of the fourth book,—as arrant commonplace as
Gray's Elegy itself. Members of a Browning society have been known
to descend earthward by reading Longfellow. If minor poets and
obvious, popular poems ever disappear, and if crowds ever go dumb,
then better and best poetry itself will be dead as King Pandion. No
"Absent-Minded Beggar," no "Recessional."
Whoever, then, will tell the truth about poetry's part in the world
of to-day and to-morrow must not only know the course of all poetry
through all the yesterdays, but must keep all its present
manifestations, all its elements, sources, and allies at his command.
Not only the lords of verse are to advise him; he shall take counsel
with scullions and potboys. It is that poet in every man, about whom
Sainte-Beuve discoursed, who can best tell of the future of poetry.
The enormous heed paid to the great and solitary poets, as if there
could be a poet without audience or reader, has distorted our vision
until we think of poetry as a quite solitary performance, a refuge
from the world. Is not poetry really a flight from self and solitude to
at least a conventional, imaginative society? Poetry by its very form is
a convention, an echo of social consent; with its aid one may forget
personal debit and credit in the great account of humanity. Now, as in
the beginning, poetry is essentially social; its future is largely a social
problem. How far, then, has man ceased to sing in crowds, and taken
to thinking by himself? What is the shrinkage, quality as well as
quantity, in the proportion of verse to prose since the invention of
printing? Is the loss of so much communal song in daily toil, in daily
merriment, like the cutting away of those forests which hold the rains
and supply the great rivers?
Waiting for complete and trustworthy studies of humanity which
shall answer some of those queries, one may venture an opinion on
the general case. Just as one feels that forests may vanish, and yet in
some way the mighty watercourses must be fed, so with poetry.
Nothing has yet been found to take the place of rhythm as sign of
social consent, the union of steps and voices in common action; and
whatever intellectual or spiritual consolation may reach the lonely
thinker, emotion still drives him back upon the sympathy of man with
man.
Human sympathy is thus at the heart of every poetic utterance,
whether humble or great; rhythm is its outward and visible, once
audible sign; and poetry, from this point of view, would therefore
seem to be an enduring element in our life.

TABLE OF CONTENTS.
————————
INTRODUCTORY ESSAY: PAGE
"The Old Case of Poetry in a New
Court."
By Francis Barton Gummere ix

POEMS OF TRAGEDY:
Greece and Rome 3
The Orient 26
Germany 44
Italy: Spain 55
Switzerland: Russia 88
Scotland: Ireland: England 120
America 172
The Sea 181

HUMOROUS POEMS:
Woman 197
Miscellaneous 239
Parodies: Imitations 396
Ingenuities: Oddities 426

INDEX: Authors and Titles 461

LIST OF ILLUSTRATIONS.
————————
JOHANN WOLFGANG von GOETHE. Frontispiece
Photogravure after a photograph from a
portrait by Stieler.
PAGE
FRANCESCA DA RIMINI 1
Dante's tale of the unhappy lovers
whom he saw in the realm of shades will
live in poetry and art. This color-plate,
from the painting by A. Cabanel, shows
their tragic death at the hand of the
enraged brother.

NATHANIEL PARKER WILLIS 9


From an engraving after the portrait by
C. L. Elliott.

THE DIVER 45
"Hark! a shriek from the crowd rang
aloud from the shore,
And behold! he is whirled in the
grasp of the main."
From photogravure after a drawing by
A. Michaelis.

ROBERT BROWNING 103


After a life-photograph by Elliott and
Fry, London.

THE FATAL COAST-TIDE 145


"The old sea-wall (he cried) is down!
The rising tide comes on apace."
From photogravure by Braun, Clement &
Co., after a painting by G. Haquette.

THE BATTLE OF THE NILE 185


"There came a burst of thunder-
sound;
The boy—Oh! where was he?
Ask of the winds that far around
With fragments strewed the sea."
From engraving after the painting by
George Arnald, A. R. A.

RICHARD HENRY STODDARD 193


After a life-photograph by Sarony, New
York.

THE PRESS-GANG 271


"But as they fetched a walk one day,
They met a press-gang crew;
And Sally she did faint away,
Whilst Ben he was brought to."
From engraving after a painting by
Alexander Johnston.

OLIVER WENDELL HOLMES 345


After a photogravure from life-
photograph by Notman, Boston.

BRET HARTE 375


From a photogravure after the original
portrait by J. Pettie

FRANCESCA DA RIMINI.
The tale of the fated lovers, Francesca and Paolo,
whose fleeting spirits Dante saw in his visit to the
realms of the dead, will always live in poetry and in art.
His brief story of their approach in mutual sympathy,
over the reading of a book, is given in our second
volume: the scene of their tragic death at the hand of
her enraged husband is the subject of this painting by
Alexandre Cabanel, the French artist.
POEMS OF TRAGEDY.

IPHIGENEIA AND AGAMEMNON.

Iphigeneia, when she heard her doom


At Aulis, and when all beside the king
Had gone away, took his right hand, and said:
"O father! I am young and very happy.
I do not think the pious Calchas heard
Distinctly what the goddess spake; old age
Obscures the senses. If my nurse, who knew
My voice so well, sometimes misunderstood,
While I was resting on her knee both arms,
And hitting it to make her mind my words,
And looking in her face, and she in mine,
Might not he, also, hear one word amiss,
Spoken from so far off, even from Olympus?"
The father placed his cheek upon her head,
And tears dropt down it; but the king of men
Replied not. Then the maiden spake once more:
"O father! sayest thou nothing? Hearest thou not
Me, whom thou ever hast, until this hour,
Listened to fondly, and awakened me
To hear my voice amid the voice of birds,
When it was inarticulate as theirs,
And the down deadened it within the nest?"
He moved her gently from him, silent still;
And this, and this alone, brought tears from her,
Although she saw fate nearer. Then with sighs:
"I thought to have laid down my hair before
Benignant Artemis, and not dimmed
Her polished altar with my virgin blood;
I thought to have selected the white flowers
To please the nymphs, and to have asked of each
By name, and with no sorrowful regret,
Whether, since both my parents willed the change,
I might at Hymen's feet bend my clipt brow;
And (after these who mind us girls the most)
Adore our own Athene, that she would
Regard me mildly with her azure eyes,—
But, father, to see you no more, and see
Your love, O father! go ere I am gone!"
Gently he moved her off, and drew her back,
Bending his lofty head far over hers;
And the dark depths of nature heaved and burst.
He turned away,—not far, but silent still.
She now first shuddered; for in him, so nigh,
So long a silence seemed the approach of death,
And like it. Once again she raised her voice:
"O father! if the ships are now detained,
And all your vows move not the gods above,
When the knife strikes me there will be one prayer
The less to them; and purer can there be
Any, or more fervent, than the daughter's prayer
For her dear father's safety and success?"
A groan that shook him shook not his resolve.
An aged man now entered, and without
One word stepped slowly on, and took the wrist
Of the pale maiden. She looked up, and saw
The fillet of the priest and calm, cold eyes.
Then turned she where her parent stood, and cried:
"O father! grieve no more; the ships can sail."

WALTER SAVAGE LANDOR.

THE SACRIFICE OF POLYXENA.


FROM "HECUBA."
[It had been determined by the victorious Greeks to
sacrifice Polyxena, the daughter of Priam, King of Ilium,
and his wife Hecuba, on the tomb of the slain Achilleus.
Odysseus, sent by the Greeks to fetch the maiden,
turned a deaf ear to the entreaties of the mother, and
Polyxena herself addresses the Greek:]

"I see thee, how beneath thy robe, O King,


Thy hand is hidden, thy face turned from mine,
Lest I should touch thee by the beard and pray:
Fear not: thou hast escaped the god of prayers
For my part. I will rise and follow thee,
Driven by strong need; yea, and not loth to die.
Lo! if I should not seek death, I were found
A cowardly, life-loving, selfish soul!
For why should I live? Was my sire not King
Of all broad Phrygia? Thus my life began;
Then I was nurtured on fair bloom of hope
To be the bride of kings; no small the suit,
I ween, of lovers seeking me: thus I
Was once—ah, woe is me! of Idan dames
Mistress and queen, 'mid maidens like a star
Conspicuous, peer of gods, except for death;
And now I am a slave: this name alone
Makes me in love with death—so strange it is."
[Later in the drama follows the account of the heroic
death of Polyxena, described to the unhappy Hecuba by
the herald Talthybius.]

"The whole vast concourse of the Achaian host


Stood round the tomb to see your daughter die.
Achilleus' son, taking her by the hand,
Placed her upon the mound, and I stayed near;
And youths, the flower of Greece, a chosen few,
With hands to check thy heifer, should she bound,
Attended. From a cup of carven gold,
Raised full of wine, Archilleus' son poured forth
Libation to his sire, and bade me sound
Silence throughout the whole Achaian host.
I, standing there, cried in the midst these words:—
'Silence, Achaians! let the host be still!
Hush, hold your voices!' Breathless stayed the crowd;
But he:—'O son of Peleus, father mine,
Take these libations pleasant to thy soul,
Draughts that allure the dead: come, drink the black
Pure maiden's blood wherewith the host and I
Sue thee: be kindly to us; loose our prows,
And let our barks go free; give safe return
Homeward from Troy to all, and happy voyage,'
Such words he spake, and the crowd prayed assent.
Then from the scabbard, by its golden hilt,
He drew the sword, and to the chosen youths
Signalled that they should bring the maid; but she,
Knowing her hour was come, spake thus, and said:
'O men of Argos, who have sacked my town,
Lo, of free will I die! Let no man touch
My body: boldly will I stretch my throat.
Nay, but I pray you set me free, then slay;
That free I thus may perish: 'mong the dead,
Being a queen, I blush to be called slave.'
The people shouted, and King Agamemnon
Bade the youths loose the maid, and set her free;
She, when she heard the order of the chiefs,
Seizing her mantle, from the shoulder down
To the soft centre of her snowy waist
Tore it, and showed her breasts and bosom fair
As in a statue. Bending then with knee
On earth, she spake a speech most piteous:—
'See you this breast, O youth? If breast you will,
Strike it; take heart: or if beneath my neck,
Lo! here my throat is ready for your sword!'
He, willing not, yet willing,—pity-stirred
In sorrow for the maiden,—with his blade
Severed the channels of her breath: blood flowed;
And she, though dying, still had thought to fall
In seemly wise, hiding what eyes should see not.
But when she breathed her life out from the blow,
Then was the Argive host in divers way
Of service parted; for some, bringing leaves,
Strewed them upon the corpse; some piled a pyre,
Dragging pine trunks and boughs; and he who bore none,
Heard from the bearers many a bitter word:—
'Standest thou, villain? hast thou then no robe,
No funeral honors for the maid to bring?
Wilt thou not go and get for her who died
Most nobly, bravest-souled, some gift?' Thus they
Spake of thy child in death:—O thou most blessed
Of women in thy daughter, most undone!"

From the Greek of EURIPIDES.


Translation of JOHN ADDINGTON SYMONDS.

PARRHASIUS.

There stood an unsold captive in the mart,


A gray-haired and majestical old man,
Chained to a pillar. It was almost night,
And the last seller from the place had gone,
And not a sound was heard but of a dog
Crunching beneath the stall a refuse bone,
Or the dull echo from the pavement rung,
As the faint captive changed his weary feet.
He had stood there since morning, and had borne
From every eye in Athens the cold gaze
Of curious scorn. The Jew had taunted him
For an Olynthian slave. The buyer came
And roughly struck his palm upon his breast,
And touched his unhealed wounds, and with a sneer
Passed on; and when, with weariness o'erspent,
He bowed his head in a forgetful sleep,
The inhuman soldier smote him, and, with threats
Of torture to his children, summoned back
The ebbing blood into his pallid face.

'T was evening, and the half-descended sun


Tipped with a golden fire the many domes
Of Athens, and a yellow atmosphere
Lay rich and dusky in the shaded street
Through which the captive gazed. He had borne up
With a stout heart that long and weary day,
Haughtily patient of his many wrongs,
But now he was alone, and from his nerves
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!

textbookfull.com

You might also like