0% found this document useful (0 votes)
3 views

Java Cookbook 4th Edition Ian F. Darwin instant download

The document provides information about the 'Java Cookbook 4th Edition' by Ian F. Darwin, which aims to assist Java developers in navigating the complexities of Java programming. It covers essential topics, including standard APIs, object-oriented techniques, and data processing, while also addressing recent changes in Java versions. The book is structured into chapters that present problems and solutions, with code examples available in public repositories for practical application.

Uploaded by

hedlybaadil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Cookbook 4th Edition Ian F. Darwin instant download

The document provides information about the 'Java Cookbook 4th Edition' by Ian F. Darwin, which aims to assist Java developers in navigating the complexities of Java programming. It covers essential topics, including standard APIs, object-oriented techniques, and data processing, while also addressing recent changes in Java versions. The book is structured into chapters that present problems and solutions, with code examples available in public repositories for practical application.

Uploaded by

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

Java Cookbook 4th Edition Ian F.

Darwin pdf
download

https://ebookname.com/product/java-cookbook-4th-edition-ian-f-
darwin/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Java Cookbook 1st Edition Ian F. Darwin

https://ebookname.com/product/java-cookbook-1st-edition-ian-f-
darwin/

Android Cookbook 2nd [early release] Edition Ian F.


Darwin

https://ebookname.com/product/android-cookbook-2nd-early-release-
edition-ian-f-darwin/

Java Extreme Programming Cookbook 1st Edition Eric M.


Burke

https://ebookname.com/product/java-extreme-programming-
cookbook-1st-edition-eric-m-burke/

Creating Yoknapatawpha Readers and Writers in Faulkner


s Fiction Studies in Major Literary Authors 1st Edition
Owen Robinson

https://ebookname.com/product/creating-yoknapatawpha-readers-and-
writers-in-faulkner-s-fiction-studies-in-major-literary-
authors-1st-edition-owen-robinson/
The Mathematical Theory of Symmetry in Solids
Representation Theory for Point Groups and Space Groups
1st Edition Christopher Bradley

https://ebookname.com/product/the-mathematical-theory-of-
symmetry-in-solids-representation-theory-for-point-groups-and-
space-groups-1st-edition-christopher-bradley/

Homeschooling 1st Edition Heidi Watkins

https://ebookname.com/product/homeschooling-1st-edition-heidi-
watkins/

MRCS revision guide limbs and spine 1st Edition Mazyar


Kanani

https://ebookname.com/product/mrcs-revision-guide-limbs-and-
spine-1st-edition-mazyar-kanani/

3D Object Processing Compression Indexing and


Watermarking 1st Edition Jean-Luc Dugelay

https://ebookname.com/product/3d-object-processing-compression-
indexing-and-watermarking-1st-edition-jean-luc-dugelay/

Marketing defined explained applied Second Edition,


Pearson New International Edition. Edition Levens

https://ebookname.com/product/marketing-defined-explained-
applied-second-edition-pearson-new-international-edition-edition-
levens/
Becoming Yellow A Short History of Racial Thinking
Michael Keevak

https://ebookname.com/product/becoming-yellow-a-short-history-of-
racial-thinking-michael-keevak/
Java Cookbook
FOURTH EDITION
Problems and Solutions for Java Developers

Ian F. Darwin
Java Cookbook
by Ian F. Darwin Copyright © 2020 RejmiNet Group, Inc.
All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein
Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business,
or sales promotional use. Online editions are also available
for most titles (http://oreilly.com). For more information,
contact our corporate/institutional sales department: 800-
998-9938 or corporate@oreilly.com.
Acquisition Editor: Zan McQuade
Development Editor: Corbin Collins
Production Editor: Beth Kelly
Copyeditor: Amanda Kersey
Proofreader: Charles Roumeliotis
Indexer: Potomac Indexing, LLC
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Rebecca Demarest
June 2001: First Edition
June 2004: Second Edition
July 2014: Third Edition
March 2020: Fourth Edition
Revision History for the Fourth Edition
2020-03-17: First Release
See http://oreilly.com/catalog/errata.csp?
isbn=9781492072584 for release details.
The O’Reilly logo is a registered trademark of O’Reilly
Media, Inc. Java Cookbook, the cover image, and related
trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author,
and do not represent the publisher’s views. While the
publisher and the author have used good faith efforts to
ensure that the information and instructions contained in
this work are accurate, the publisher and the author
disclaim all responsibility for errors or omissions, including
without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information
and instructions contained in this work is at your own risk.
If any code samples or other technology this work contains
or describes is subject to open source licenses or the
intellectual property rights of others, it is your
responsibility to ensure that your use thereof complies with
such licenses and/or rights.
978-1-492-07258-4
[LSI]
Dedication
In Memoriam
Andrej Cerar Darwin 1989-2014
Son, friend, fellow writer, and craftsman.
Preface

Like any of the most-used programming languages, Java


has its share of detractors, advocates, issues, quirks,1 and a
learning curve. The Java Cookbook aims to help the Java
developer get up to speed on some of the most important
parts of Java development. I focus on the standard APIs and
some third-party APIs, but I don’t hesitate to cover
language issues as well.
This is the fourth edition of this book, and it has been
shaped by many people and by the myriad changes that
Java has undergone over its first two decades of popularity.
Readers interested in Java’s history can refer to Appendix
A.
Java 11 is the current long-term supported version, but
Java 12 and 13 are out. Java 14 is in early access and
scheduled for final release the very same day as this book’s
fourth edition. The new cadence of releases every six
months may be great for the Java SE development team at
Oracle and for click-driven, Java-related news sites, but it
“may cause some extra work” for Java book authors, since
books typically have a longer revision cycle than Java now
does! Java 9, which came out after the previous edition of
this book, was a breaking release, the first release in a very
long time to break backwards compatibility, primarily the
Java module system. Everything in the book is assumed to
work on any JVM that is still being used to develop code.
Nobody should be using Java 7 (or anything before it!) for
anything, and nobody should be doing new development in
Java 8. If you are, it’s time to move on!
The goal of this revision is to keep the book up to date with
all this change. While cutting out a lot of older material,
I’ve added information on new features such as Modules
and the interactive JShell, and I’ve updated a lot of other
information along the way.
Who This Book Is For
I’m going to assume that you know the basics of Java. I
won’t tell you how to println a string, nor how to write a
class that extends another and/or implements an interface.
I presume you’ve taken a Java course such as Learning
Tree’s Introduction or that you’ve studied an introductory
book such as Head First Java, Learning Java, or Java in a
Nutshell (O’Reilly). However, Chapter 1 covers some
techniques that you might not know very well and that are
necessary to understand some of the later material. Feel
free to skip around! Both the printed version of the book
and the electronic copy are heavily cross-referenced.

What’s in This Book?


Java has seemed better suited to “development in the
large,” or enterprise application development, than to the
one-line, one-off script in Perl, Awk, or Python. That’s
because it is a compiled, object-oriented language.
However, this suitability has changed somewhat with the
appearance of JShell (see Recipe 1.4). I illustrate many
techniques with shorter Java class examples and even code
fragments; some of the simpler ones will be shown using
JShell. All of the code examples (other than some one- or
two-liners) are in one of my public GitHub repositories, so
you can rest assured that every fragment of code you see
here has been compiled, and most have been run recently.
Some of the longer examples in this book are tools that I
originally wrote to automate some mundane task or
another. For example, a tool called MkIndex (in the javasrc
repository) reads the top-level directory of the place where
I keep my Java example source code, and it builds a
browser-friendly index.html file for that directory. Another
example is XmlForm, which was used to convert parts of the
manuscript from XML into the form needed by another
publishing software. XmlForm also handled—by use of
another program, GetMark—full and partial code insertions
from the javasrc directory into the book manuscript. XmlForm
is included in the Github repository I mentioned, as is a
later version of GetMark, though neither of these was used in
building the fourth edition. These days, O’Reilly’s Atlas
publishing software uses Asciidoctor, which provides the
mechanism we use for inserting files and parts of files into
the book.

Organization of This Book


Let’s go over the organization of this book. Each chapter
consists of a handful of recipes, short sections that describe
a problem and its solution, along with a code example. The
code in each recipe is intended to be largely self-contained;
feel free to borrow bits and pieces of any of it for use in
your own projects. The code is distributed with a Berkeley-
style copyright, just to discourage wholesale reproduction.
I start off Chapter 1, Getting Started: Compiling and
Running Java, by describing some methods of compiling
your program on different platforms, running them in
different environments (browser, command line, windowed
desktop), and debugging.
Chapter 2, Interacting with the Environment, moves from
compiling and running your program to getting it to adapt
to the surrounding countryside—the other programs that
live in your computer.
The next few chapters deal with basic APIs. Chapter 3,
Strings and Things, concentrates on one of the most basic
but powerful data types in Java, showing you how to
assemble, dissect, compare, and rearrange what you might
otherwise think of as ordinary text. This chapter also
covers the topic of internationalization/localization so that
your programs can work as well in Akbar, Afghanistan,
Algiers, Amsterdam, and Angleterre as they do in Alberta,
Arkansas, and Alabama.
Chapter 4, Pattern Matching with Regular Expressions,
teaches you how to use the powerful regular expressions
technology from Unix in many string-matching and pattern-
matching problem domains. Regex processing has been
standard in Java for years, but if you don’t know how to use
it, you may be reinventing the flat tire.
Chapter 5, Numbers, deals both with built-in numeric types
such as int and double, as well as the corresponding API
classes (Integer, Double, etc.) and the conversion and testing
facilities they offer. There is also brief mention of the “big
number” classes. Because Java programmers often need to
deal in dates and times, both locally and internationally,
Chapter 6, Dates and Times, covers this important topic.
The next few chapters cover data processing. As in most
languages, arrays in Java are linear, indexed collections of
similar objects, as discussed in Chapter 7, Structuring Data
with Java. This chapter goes on to deal with the many
Collections classes: powerful ways of storing quantities of
objects in the java.util package, including use of Java
Generics.
Despite some syntactic resemblance to procedural
languages such as C, Java is at heart an Object-Oriented
Programming (OOP) language, with some important
Functional Programming (FP) constructs skilfully blended
in. Chapter 8, Object-Oriented Techniques, discusses some
of the key notions of OOP as it applies to Java, including the
commonly overridden methods of java.lang.Object and the
important issue of design patterns. Java is not, and never
will be, a pure FP language. However, it is possible to use
some aspects of FP, increasingly so with Java 8 and its
support of lambda expressions (a.k.a. closures). This is
discussed in Chapter 9, Functional Programming
Techniques: Functional Interfaces, Streams, and Parallel
Collections.
The next chapter deals with aspects of traditional input and
output. Chapter 10, Input and Output: Reading, Writing,
and Directory Tricks, details the rules for reading and
writing files (don’t skip this if you think files are boring;
you’ll need some of this information in later chapters). The
chapter also shows you everything else about files—such as
finding their size and last-modified time—and about
reading and modifying directories, creating temporary files,
and renaming files on disk.
Big data and data science have become a thing, and Java is
right in there. Apache Hadoop, Apache Spark, and much
more of the big data infrastructure is written in, and
extensible with, Java, as described in Chapter 11, Data
Science and R. The R programming language is popular
with data scientists, statsticians, and other scientists.
There are at least two reimplementations of R coded in
Java, and Java can also be interfaced directly with the
standard R implementation in both directions, so this
chapter covers R as well.
Because Java was originally promulgated as the
programming language for the internet, it’s only fair to
spend some time on networking in Java. Chapter 12,
Network Clients, covers the basics of network
programming from the client side, focusing on sockets.
Today so many applications need to access a web service,
primarily RESTful web services, that this seemed to be
necessary. I’ll then move to the server side in Chapter 13,
Server-Side Java, wherein you’ll learn some server-side
programming techniques.
One simple text-based representation for data interchange
is JSON, the JavaScript object notation. Chapter 14,
Processing JSON Data, describes the format and some of
the many APIs that have emerged to deal with it.
Chapter 15, Packages and Packaging, shows how to create
packages of classes that work together. This chapter also
talks about deploying (a.k.a. distributing and installing)
your software.
Chapter 16, Threaded Java, tells you how to write classes
that appear to do more than one thing at a time and let you
take advantage of powerful multiprocessor hardware.
Chapter 17, Reflection, or “A Class Named Class”, lets you
in on such secrets as how to write API cross-reference
documents mechanically and how web servers are able to
load any old Servlet—never having seen that particular
class before—and run it.
Sometimes you already have code written and working in
another language that can do part of your work for you, or
you want to use Java as part of a larger package. Chapter
18, Using Java with Other Languages, shows you how to
run an external program (compiled or script) and also
interact directly with native code in C/C++ or other
languages.
There isn’t room in a book this size for everything I’d like
to tell you about Java. The Afterword presents some closing
thoughts and a link to my online summary of Java APIs that
every Java developer should know about.
Finally, Appendix A, Java Then and Now, gives the storied
history of Java in a release-by-release timeline, so whatever
version of Java you learned, you can jump in here and get
up to date quickly.
So many topics, and so few pages! Many topics do not
recieve 100% coverage; I’ve tried to include the most
important or most useful parts of each API. To go beyond,
check the official javadoc pages for each package; many of
these pages have some brief tutorial information on how
the package is to be used.
Besides the parts of Java covered in this book, two other
platform editions, Java ME and Java EE, have been
standardized. Java Micro Edition (Java ME) is concerned
with small devices such as handhelds, cell phones, and fax
machines. At the other end of the size scale—large server
machines—there’s Eclipse Jakarta EE, replacing the former
Java EE, which in the last century was known as J2EE.
Jakarta EE is concerned with building large, scalable,
distributed applications. APIs that are part of Jakarta EE
include Servlets, JavaServer Pages, JavaServer Faces,
JavaMail, Enterprise JavaBeans (EJBs), Container and
Dependency Injection (CDI), and Transactions. Jakarta EE
packages normally begin with “javax” because they are not
core packages. This book mentions but a few of these;
there is also a Java EE 8 Cookbook by Elder Moraes
(O’Reilly) that covers some of the Jakarta EE APIs, as well
as an older Java Servlet & JSP Cookbook by Bruce Perry
(O’Reilly).
This book doesn’t cover Java Micro Edition, Java ME. At all.
But speaking of cell phones and mobile devices, you
probably know that Android uses Java as its language.
What should be comforting to Java developers is that
Android also uses most of the core Java API, except for
Swing and AWT, for which it provides Android-specific
replacements. The Java developer who wants to learn
Android may consider looking at my Android Cookbook
(O’Reilly), or the book’s website.

Java Books
A lot of useful information is packed into this book.
However, due to the breadth of topics, it is not possible to
give book-length treatment to any one topic. Because of
this, the book contains references to many websites and
other books. In pointing out these references, I’m hoping to
serve my target audience: the person who wants to learn
more about Java.
O’Reilly publishes, in my opinion, the best selection of Java
books on the market. As the API continues to expand, so
does the coverage. Check out the complete list of O’Reilly’s
collection of Java books; you can buy them at most
bookstores, both physical and virtual. You can also read
them online through the O’Reilly Online Learning Platform,
a paid subscription service. And, of course, most are now
available in ebook format; O’Reilly ebooks are DRM free, so
you don’t have to worry about their copy-protection scheme
locking you into a particular device or system, as you do
with certain other publishers.
Though many books are mentioned at appropriate spots in
the book, a few deserve special mention here.
First and foremost, David Flanagan and Benjamin Evan’s
Java in a Nutshell (O’Reilly) offers a brief overview of the
language and API and a detailed reference to the most
essential packages. This is handy to keep beside your
computer. Head First Java by Bert Bates and Kathy Sierra
offers a much more whimsical introduction to the language
and is recommended for the less experienced developer.
Java 8 Lambdas (Warburton, O’Reilly) covers the Lambda
syntax introduced in Java 8 in support of functional
programming and more concise code in general.
Java 9 Modularity: Patterns and Practices for Developing
Maintainable Applications by Sander Mak and Paul Bakker
(O’Reilly) covers the important changes made in the
language in Java 9 for the Java module system.
Java Virtual Machine by Jon Meyer and Troy Downing
(O’Reilly) will intrigue the person who wants to know more
about what’s under the hood. This book is out of print but
can be found used and in libraries.
A definitive (and monumental) description of programming
the Swing GUI is Java Swing by Robert Eckstein et al.
(O’Reilly).
Java Network Programming and Java I/O, both by Elliotte
Harold (O’Reilly), are also useful references.
For Java Database work, Database Programming with JDBC
& Java by George Reese (O’Reilly) and Pro JPA 2: Mastering
the Java Persistence API by Mike Keith and Merrick
Schincariol (Apress) are recommended. Or my forthcoming
overview of Java Database.
Although the book you’re now reading doesn’t have much
coverage of the Java EE, I’d like to mention two books on
that topic:
Arun Gupta covers the Enterprise Edition in Java EE 7
Essentials (O’Reilly).
Adam Bien’s Real World Java EE Patterns: Rethinking
Best Practices offers useful insights in designing and
implementing an Enterprise application.
You can find more at the O’Reilly website.
Finally, although it’s not a book, Oracle has a great deal of
Java information on the web. This web page used to feature
a large diagram showing all the components of Java in a
“conceptual diagram.” An early version of this is shown in
Figure P-1; each colored box is a clickable link to details on
that particular technology.

Figure P-1. Java conceptual diagram from Oracle documentation

For better or for worse, newer versions of Java have


replaced this with a text page; for Java 13 the page is at
https://docs.oracle.com/en/java/javase/13.

General Programming Books


Donald E. Knuth’s The Art of Computer Programming
(Addison-Wesley) has been a source of inspiration to
generations of computing students since its first
publication in 1968. Volume 1 covers Fundamental
Algorithms, Volume 2 is Seminumerical Algorithms, Volume
3 is Sorting and Searching, and Volume 4A is Combinatorial
Algorithms, Part 1. The remaining volumes in the projected
series are not completed. Although his examples are far
from Java (he invented the hypothetical assembly language
MIX for his examples), many of his discussions of
algorithms—of how computers ought to be used to solve
real problems—are as relevant today as they were years
ago.2
Though its code examples are quite dated now, the book
The Elements of Programming Style by Brian Kernighan
and P. J. Plauger (McGraw-Hill) set the style (literally) for a
generation of programmers with examples from various
structured programming languages. Kernighan and Plauger
also wrote a pair of books, Software Tools (Addison-Wesley)
and Software Tools in Pascal (Addison-Wesley), which
demonstrated so much good advice on programming that I
used to advise all programmers to read them. However,
these three books are dated now; many times I wanted to
write a follow-on book in a more modern language. Instead
I now defer to The Practice of Programming, Kernighan’s
follow-on—cowritten with Rob Pike (Addison-Wesley)—to
the Software Tools series. This book continues the Bell
Labs tradition of excellence in software textbooks. In
previous editions of this book, I had even adapted one bit of
code from their book, their CSV parser. Finally, Kernighan
recently published UNIX: A History and a Memoir, his take
on the story of Unix.
See also The Pragmatic Programmer by Andrew Hunt and
David Thomas (Addison-Wesley).

Design Books
Peter Coad’s Java Design (PTR-PH/Yourdon Press)
discusses the issues of object-oriented analysis and design
specifically for Java. Coad is somewhat critical of Java’s
implementation of the observable-observer paradigm and
offers his own replacement for it.
One of the most famous books on object-oriented design in
recent years is Design Patterns by Erich Gamma, Richard
Helm, Ralph Johnson, and John Vlissides (Addison-Wesley).
These authors are often collectively called the “Gang of
Four,” resulting in their book sometimes being referred to
as the GoF book. One of my colleagues called it “the best
book on object-oriented design ever,” and I agree; at the
very least, it’s among the best.
Refactoring by Martin Fowler (Addison-Wesley) covers a lot
of “coding cleanups” that can be applied to code to improve
readability and maintainability. Just as the GoF book
introduced new terminology that helps developers and
others communicate about how code is to be designed,
Fowler’s book provided a vocabulary for discussing how it
is to be improved. But this book may be less useful than
others; many of the refactorings now appear in the
Refactoring Menu of the Eclipse IDE (see Recipe 1.3).
Two important streams of methodology theories are
currently in circulation. The first is collectively known as
Agile methods, and its best-known members are Scrum and
Extreme Programming (XP). XP (the methodology, not that
really old flavor of Microsoft’s OS) is presented in a series
of small, short, readable texts led by its designer, Kent
Beck. The first book in the XP series is Extreme
Programming Explained (Addison-Wesley). A good overview
of all the Agile methods is Jim Highsmith’s Agile Software
Development Ecosystems (Addison-Wesley).
Another group of important books on methodology,
covering the more traditional object-oriented design, is the
UML series led by “the Three Amigos” (Booch, Jacobson,
and Rumbaugh). Their major works are the UML User
Guide, UML Process, and others. A smaller and more
approachable book in the same series is Martin Fowler’s
UML Distilled.

Conventions Used in This Book


This book uses the following conventions.

Programming Conventions
I use the following terminology in this book. A program
means any unit of code that can be run: from a five-line
main program, to a servlet or web tier component, an EJB,
or a full-blown GUI application. Applets were Java
programs for use in a web browser; these were popular for
a while but barely exist today. A servlet is a Java component
built using Jakarta EE APIs for use in a web server,
normally via HTTP. EJBs are business-tier components built
using Jakarta APIs. An application is any other type of
program. A desktop application (a.k.a. client) interacts with
the user. A server program deals with a client indirectly,
usually via a network connection (usually HTTP/HTTPS
these days).
The examples shown are in two varieties. Those that begin
with zero or more import statements, a javadoc comment,
and a public class statement are complete examples. Those
that begin with a declaration or executable statement, of
course, are excerpts. However, the full versions of these
excerpts have been compiled and run, and the online
source includes the full versions.
Recipes are numbered by chapter and number, so, for
example, Recipe 8.1 refers to the first recipe in Chapter 8.

Typesetting Conventions
The following typographic conventions are used in this
book:
Italic
Used for commands, filenames, and example URLs. It is
also used for emphasis and to define new terms when
they first appear in the text.

Constant width
Used in code examples to show partial or complete Java
source code program listings. It is also used for class
names, method names, variable names, and other
fragments of Java code.

Constant width bold


Used for user input, such as commands that you type on
the command line.

Constant width italic


Shows text that should be replaced with user-supplied
values or by values determined by context.

TIP
This element signifies a tip or suggestion.
NOTE
This element signifies a general note.

WARNING
This icon indicates a warning or caution.

Code Examples
The code samples for this book are on the author’s GitHub.
Most are in the repository javasrc, but a few are pulled in
from one other repository, darwinsys-api. Details on
downloading these are in Recipe 1.6.
Many programs are accompanied by an example showing
them in action, run from the command line. These will
usually show a prompt ending in either $ for Unix or > for
Windows, depending on which computer I was using the
day I wrote that example. If there is text before this prompt
character, it can be ignored. It may be a pathname or a
hostname, again, depending on the system.
These examples will usually also show the full package
name of the class because Java requires this when starting
a program from the command line. And because that will
remind you which subdirectory of the source repository to
find the source code in, I won’t be pointing it out explicitly
very often.
We appreciate, but generally do not require, attribution. An
attribution usually includes the title, author, publisher, and
ISBN. For example: “Java Cookbook by Ian F. Darwin
(O’Reilly). Copyright 2020 RejmiNet Group, Inc., 978-1-
492-07258-4.”
If you feel your use of code examples falls outside fair use
or the permission given above, feel free to contact us at
permissions@oreilly.com.

O’Reilly Online Learning

NOTE
For more than 40 years, O’Reilly Media has provided technology and
business training, knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their


knowledge and expertise through books, articles,
conferences, and our online learning platform. O’Reilly’s
online learning platform gives you on-demand access to live
training courses, in-depth learning paths, interactive
coding environments, and a vast collection of text and video
from O’Reilly and 200+ other publishers. For more
information, please visit http://oreilly.com.

Comments and Questions


As mentioned earlier, I’ve tested all the code on at least one
of the reference platforms, and most on several. Still, there
may be platform dependencies, or even bugs, in my code or
in some important Java implementation. Please report any
errors you find, as well as your suggestions for future
editions, by writing to:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
There is a web page for this book where we list errata,
examples, and any additional information. It can be
accessed at
http://shop.oreilly.com/product/0636920304371.do.
Email bookquestions@oreilly.com to comment or ask
technical questions about this book.
For more information about our books, courses,
conferences, and news, see our website at
http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
The O’Reilly site lists errata. You’ll also find the source
code for all the Java code examples to download; please
don’t waste your time typing them again! For specific
instructions, see Recipe 1.6.

Acknowledgments
I wrote in the Afterword to the first edition that “writing
this book has been a humbling experience.” I should add
that maintaining it has been humbling, too. While many
have been lavish with their praise—one very kind reviewer
called it “arguably the best book ever written on the Java
programming language”—I have been humbled by the
number of errors and omissions in earlier editions. I have
endeavored to correct these.
My life has been touched many times by the flow of the
fates bringing me into contact with the right person to
show me the right thing at the right time. Steve Munro,
with whom I’ve long since lost touch, introduced me to
computers when we were in the same class in high school—
in particular an IBM 360/30 at the Toronto Board of
Education that was bigger than a living room, had 32 or
64K (not M or G!) of memory, and had perhaps the power of
a PC/XT. The late Herb Kugel took me under his wing at the
University of Toronto while I was learning about the larger
IBM mainframes that came later. Terry Wood and Dennis
Smith at the University of Toronto introduced me to mini-
and micro-computers before there was an IBM PC. On
evenings and weekends, the Toronto Business Club of
Toastmasters International and Al Lambert’s Canada
SCUBA School allowed me to develop my public speaking
and teaching abilities. Several people at the University of
Toronto, but especially Geoffrey Collyer, taught me the
features and benefits of the Unix operating system at a
time when I was ready to learn it.
Thanks to the many Learning Tree instructors and students
who showed me ways of improving my presentations. I still
teach for “The Tree” and recommend their courses for the
busy developer who wants to zero in on one topic in detail
over four days.
Closer to this project, Tim O’Reilly believed in my “little
Lint book” when it was just a sample chapter from a
proposed longer work, enabling my early entry into the
rarefied circle of O’Reilly authors. Years later, Mike
Loukides encouraged me to keep trying to find a Java book
idea that both he and I could work with. And he stuck by
me when I kept falling behind the deadlines. Mike also read
the entire manuscript and made many sensible comments,
some of which brought flights of fancy down to earth.
Jessamyn Read turned many faxed and emailed scratchings
of dubious legibility into the quality illustrations you see in
this book. And many, many other talented people at O’Reilly
helped put this book into the form in which you now see it.
The code examples are now dynamically included (so
updates get done faster) rather than pasted in. My son (and
functional programming developer) Benjamin Darwin
helped meet the deadline by converting almost the entire
code base to O’Reilly’s newest “include” mechanism and by
resolving a couple of other non-Java presentation issues.
He also helped make Chapter 9 clearer and more
functional.

At O’Reilly
For this fourth edition of the book, Suzanne McQuade was
the editorial overseer, and Corbin Collins the principal
editor. Corbin was especially meticulous in checking the
manuscript. Meghan Blanchette, Sarah Schneider, Adam
Witwer, Melanie Yarbrough, and the many production
people listed on the Copyright page all played a part in
getting the third edition ready for you to read. Thanks to
Mike Loukides, Deb Cameron, and Marlowe Shaeffer for
editorial and production work on the second edition.

Technical Reviewers
For the fourth edition I was blessed to have two very
thorough technical reviewers, Sander Mak and Daniel
Hinojosa. Many issues that I hadn’t considered during the
main revision were called out by these two, leading to
extensive rewrites and changes in the last few weeks
before the O’Reilly production team took over. Thanks so
much to both of you!
Another Random Document on
Scribd Without Any Related Topics
proper thing to do so in prison. It certainly was indiscreet, and it is
difficult to see how, if it was justifiable to resort to this measure in
order to save the life of a prisoner, it could be argued that a medical
officer would not be equally justified in cutting off the injured or
diseased arm of a prisoner, in spite of his protestations, in order to
save his life. It is one thing to place the liberties of men, and
another thing altogether to place their lives in the hands of officials.
There is no official and no number of officials—by whatever name
called—good enough to be entrusted, unchecked by public
observation, with the lives of their fellow-citizens; and there is no
criminal bad enough to be immured from the public gaze and placed
wholly under the control of anyone. It is not that the officials are
bad; they are no worse than unofficial persons and no better, and
there is far more danger from those who have gained a reputation
for humanity and for enlightened opinions, even when they have
deserved the reputation, than from the others, because the former
are likely to be left more to themselves on account of their good
name. Few who read this could be trusted to do as good a day’s
work at the end of the year as they did at the beginning, if there
were not someone to check and criticise them.
Here and there, now and then, there are violent outcry and
excitement because of some administrative scandal, and there is
seldom much in it; but there is no continued and intelligent interest
in administration on the part of the public. If a man do not fulfil his
contract his employer may accept an excuse once or even twice; but
if his failure continue he will find himself out of a job, and someone
less incompetent or unfortunate will be sought and put in his place.
In the public service excuses and exceptions are so much the rule
that it would be easy to form a library of blue books containing
them, printed and paid for at the public expense.
Only ordinary cases of domestic sickness need be treated in prison,
and such ailments or injuries as are dealt with in the outdoor
department of a general hospital. In Scotland there is little
inducement to prisoners to feign sickness, as there is no automatic
change in their diet or location as a result of their being placed on
the sick list. The doctor may or may not remove them from their
cells and alter their diet. So far as the Act of Parliament is concerned
the treatment of the sick lies wholly in his discretion, and there is no
power granted to any authority to interfere with or overturn his
decision. He may be questioned as to the reason for his conduct;
and if foolish enough or weak enough to be persuaded into altering
it, in order to please some higher official, he may do so; but the Act
of Parliament is absolutely specific in the matter, and refers the sick
not to the Commissioners, but to the surgeon of the prison.
It is much easier for a man to carry out an instruction received from
above, than to assert and act on the powers conferred on him by
statute; but it is not right to do so, and in so far as he is subservient
he is unfaithful to his trust. Patients cannot be treated by
correspondence. No man, however highly placed, is infallible. Better
that the man on the spot should accept his responsibilities frankly,
even though he do make mistakes, than that he should look to
someone who is not present to direct him in a case of difficulty. No
medical man need want for help from his neighbours, and he can
easily get someone of approved skill to assist him in the diagnosis or
treatment of a difficult case. It is quite proper that his actions should
be scrutinised, but it is quite wrong that the scrutiny should take
place in private. The statute has recognised this principle, and has
ordered that a public enquiry should take place on the occasion of
the death of any prisoner in prison. The relatives of the prisoner are
there entitled to put any questions to the officials, personally or
through an agent; and the Sheriff has to be satisfied that all
reasonable care and skill have been exercised in the case.
Private official enquiries give opportunity for petty persecution on
the part of any Jack-in-office who fancies his abilities are equal to his
position, and whose spleen may be raised against better men than
himself. No man eminent in his profession would be likely to be
guilty of such conduct, but the occupation of some positions does
not necessarily imply professional eminence, though it may infer
social influence.
The Medical Officer has not an arduous task in treating the sick. His
work practically consists of patching up old offenders, in the
knowledge that he is prolonging their lives and their uselessness, to
the injury of the public. Many of them would have been dead long
ago as the result of their excesses had they not been interfered
with. It is well that their lives should be prolonged and their health
improved, but only if some security is taken that they use their
powers to better purpose in the future than they have done in the
past. There is no sense in the State doing anything for anybody
without a reasonable guarantee that the person benefited will not
use the benefit to the injury of the community. Many are cured of
diseases in various public institutions, and turned loose to live on
others for the rest of their lives. There is an increasing number of
young people who, having suffered from some serious illness, have
been saved from death, but have been left permanently crippled to
some extent in one or other of their organs. They are not fit for the
work they once engaged in, but they are fit for some work, and so
far as can be seen, they have no intention of performing any. A
number of them drift to the prison and on the strength of their
infirmity try to get special treatment. The special treatment they
require cannot be had there, nor is there any place at present where
it can be had.
The untried prisoner is permitted to wear his own clothing, provided
it is clean and that he can have it changed with sufficient frequency.
He may hire furniture and pay for the cleaning of his cell. He may
have visits from those of his friends he desires to see; and he may
correspond with them, provided that in the conversation and
correspondence there is nothing said or written regarding the charge
against him. All letters to and from him are read and censored on
behalf of the Governor. Prisoners are not allowed to see and
converse with their friends without the presence of a prison official.
The prisoner is put in a box with a latticed front, and his visitor is
placed in another box opposite. Between the two boxes there is
space for a warder to move. He can see the occupants of both
boxes, each of whom can only see the person in the box opposite.
When a number of prisoners are having visitors at the same time,
there is a shouting and gabbling that makes conversation difficult.
Convicted prisoners and convicts of the first class may receive a
letter and a visit from a friend once in three months, provided their
conduct and industry have been satisfactory. Before their entry into
the first class convicts may receive one, two, or three letters and
visits in the year, according to the class they have reached. After
being a year in the first class they may be placed in a special class,
receiving a letter and a visit once in two months.
The prisoner sees his agent in view of but outwith the hearing of the
warder. He may have his food sent in to him by his friends, provided
it is sufficient in quality and amount, but he may not have part of a
meal sent in. He may also receive newspapers, magazines, or books.
Any or all of these privileges may be granted or withdrawn at the
discretion of the Visiting Committee. It is questionable whether it is
right that they should be granted as privileges. The man is, in the
eyes of the law, presumed to be innocent of the offence charged
against him; and his detention is only justifiable on the ground that
he might fail to appear at court for trial. That being so, he ought not
to require permission from any committee or official before he is
allowed to feed, clothe, and amuse himself; and he should only be
prevented from doing so if his act is detrimental to his own health or
that of the other inmates of the prison. This might cause more
trouble to the officials concerned, but the primary object of the
system ought not to be the saving them trouble.
The untried prisoner may have a pint of wine or a pint of beer daily,
but on no account is he permitted to smoke. This is a curious
restriction nowadays, and there is not the faintest show of reason for
its exercise. The proper attitude towards the untried prisoner is not
that implied in the question “Why should he be allowed to do this?”
The question ought always to be “Why should he not be allowed to
do what he wishes?” and this would be the question if the theory
that presumes an untried prisoner’s innocence were put in practice.
He is detained for the convenience of the public, not for his own,
and his liberty should be curtailed as little as possible consistent with
good order.
There are very few civil prisoners in Scotland. Failure to pay aliment
may entail on a prisoner imprisonment, at the instance and expense
of his creditor, for a period of six weeks. At the end of that time the
prisoner is free from similar proceedings for six months, but the
costs are added to his original debt. He has some of the privileges of
an untried prisoner. Failure to pay taxes may cause a man to be
imprisoned under similar conditions. Persons sent to prison for failing
to have their children vaccinated are treated by the same rule, and
persons condemned to indefinite imprisonment for contempt of
court.
In Scotland we claim that we do not imprison for debt other than
aliment, rates, or taxes; but the rule is evaded by process of law,
and the Prison Commissioners are used as debt collectors in some
cases. Technically this is not so, but in practice it occurs. X 31, a
woman, has obtained jewellery on the hire-purchase system. She is
the wife of a labouring man, and there is room for the suspicion that
she has been tempted by the seller. A number of payments are
made, then the husband loses his employment, and she is not only
cut off from the means of paying her instalments, but has not
money to get food. She pawns or otherwise disposes of the
jewellery, and is called upon either to pay for it or return it. Her
intention may be to pay, but she is not able. She is summoned to
appear at Court, and fails to do so. In her absence a decree is
granted ordaining her to deliver the jewellery to the person from
whom she obtained it, in terms of the contract made between them.
Failing to do this, she is seized and carried off to prison, on a
warrant obtained for Contempt of Court, inasmuch as she had not
obeyed its decree. All her friends become alarmed, and by their
united efforts the money to satisfy the creditor may be obtained. If
this is not done she may be kept in prison for an indefinite period at
his expense. Had she contracted a debt with the grocer for food, or
with a dressmaker for clothing, they could not have imprisoned her if
she did not pay them, even though they desired to do so. They are
thus at a serious disadvantage, so far as the exercise of pressure is
concerned, compared with the hire-purchase trader; but the
ingenious among them who regret the abolition of imprisonment for
debt may revive it in effect by selling groceries and clothes on a
hire-purchase contract.
The routine treatment to which the convict is subjected is much
more severe than that which is applied to the ordinary prisoner, and
it does as little good.[3] It is a system of repression mainly; a sitting
on the safety-valve that is apt to provoke outbursts of temper and
violence resulting in assault. These may be punished with the lash. A
power which is not possessed by the Judges of the High Court is
granted to the Prison Commissioners. It is considered necessary in
order to maintain the system, but as no one claims that the system
is in any degree reformatory, it becomes a question whether it is
worth maintaining.
The same man who is at one time a convicted prisoner in an
ordinary prison may at another time be undergoing penal servitude.
While he is in an ordinary prison there is neither power nor occasion
to order him the severe punishments which may be inflicted on
convicts. If he need the lash when he is sent to penal servitude,
there is at least the presumption that the cause lies as much in the
character of the life he is compelled to lead as in the character of the
man. The more punishment inflicted on prisoners in a prison the
stronger the probability is that the place is badly managed.
Repression is necessary, no doubt, but repressive powers should
only co-exist with power to reward. Even a donkey will go further
after a carrot than when driven by a stick. It never does any good to
a man to treat him as a machine, and the tendency to do so under
the name of discipline is a root vice of the system. In the convict
prison, as in the ordinary prison, during the last few years the
grinding mechanical routine has been relaxed, and the amazing
discovery has been made that it is easier and better to manage men
if you recognise that they are men than to regard them as mere
numbers. There has even been talk of reformation resulting from the
changes that have taken place, and to judge by some magazine and
newspaper articles from the pens of enthusiastic and ignorant
visitors, one would think the prison had become a kind of paradise.
That other men’s behaviour towards us will largely be determined on
our behaviour towards them is no new discovery, and that more
considerate treatment by officials should result in better conduct on
the part of prisoners need surprise no one; but that this better
conduct necessarily implies that they will live in conformity with the
laws when liberated does not follow at all. You may improve a man’s
conduct in prison as you may improve his mental condition in a
lunatic asylum, but you never know how he will behave outside until
you put him there; and if we acted on the knowledge of this fact we
should see that persons liberated from any institution are placed in
proper positions outside—that they should be guided and helped in
so far as they need guidance and help—so that there would be less
excuse for their recurring to their old habits and conduct, and less
chance of their relapse into the condition and actions for which we
have dealt with them.
Of late years short sentences have been generally denounced on the
ground that there is no time to reform a prisoner who is only under
the influence of the system for a few days. This would be a
reasonable objection if those who are sent to prison for long periods
were thereby made better, but that is precisely what cannot be
shown; for the longer a person is in prison the less fit he is on
liberation to take his place in the community. So that if short
sentences are bad, long sentences are worse, from the standpoint of
the reformer. A person sent to prison for a few days is usually the
cleaner for his experience. Imprisonment has kept him off the
streets for a time. It has also caused him to lose his job, and, as
usually the short-time prisoner is not a person of means, his position
is worse after his imprisonment than it was before. He has to earn
his living by his work, if he would avoid coming into conflict with the
law; and if he has no means of livelihood it is easy to see that he will
find it difficult to avoid recommittal.
In this respect the long-sentence prisoner resembles him, but in
addition he has acquired habits in prison that are a hindrance to him
outside.

CHAPTER V

THE PRISONER ON LIBERATION


His condition—His need—Alleged persecution of ex-
prisoners—Discharged prisoners’ aid societies—
Work—Temptations—The discharged female
offender—The attitude of women towards her
—“Homes”—The women’s objections to them—Pay
—The religious atmosphere and the harmful
associations—The effect of imprisonment.

W HILE in prison a man has been cut off from the life of the
world. He has had no visits from his friends save once in three
months, and as there is no newspaper which he is permitted to see,
he is ignorant of any changes that may have occurred during the
time of his incarceration. Those who have at any time been confined
to the house by sickness may dimly appreciate his condition.
Although they may have been visited by their friends; kept in touch
with social movements in which they were interested; and generally
helped to a knowledge of passing events of interest; they must have
found something strange in the aspect of things when they were
first allowed out.
Even after a holiday it takes a man some little time to get the hang
of his work. In the case of the liberated prisoner the difficulty is
greatly aggravated. He may find that during his seclusion friends
have died or have left the district, and if a first offender who feels
the degradation he has brought on himself, he is likely to be
sensitive as to the bearing of others towards him. He needs help; he
dreads rebuff; and he does not know where to seek assistance. He
may readily misinterpret the attitude of others towards him and
imagine that men whom he has known are giving him the cold
shoulder, when, in fact, they have not seen him. He has been shut
off from the company of others, and he feels the need of fellowship
with someone. He can always have that from those who, like
himself, have been through the mill; and he may be led by them into
further mischief.
Our interference with the offender results in his removal, for a time,
from the associations and habits to which he has been accustomed;
to that extent the power over him of these associations and habits
may be weakened; but no matter where we put him, we cannot
hinder him from learning new habits, and these may or may not be
useful to him on his liberation. The more powerful the influence of
his later interests the less likely he is to seek to return to his old
pursuits. The thing which no man can do without is fellowship or
comradeship of some sort. He will seek it even although in the
process he may be injured thereby; and it is because drink makes
the company of some men more tolerable to each other that so
many take it. It is not so much that they wish to get drunk; they
could do that alone; and at first, at any rate, the drink is not taken
merely to intoxicate, but largely to stimulate sociability. The person
who has been pent up in an institution for a prolonged period has
not learned habits of a sociable character, but quite the contrary;
and when he gets out he knows that he will more easily become a
part of good company if he takes drink, for thereby he will be set
free from the feeling of restraint to which he has been subjected.
There has been a great deal of talk about police persecution of
liberated prisoners. In some cases the official zeal of a policeman
may cause him to act towards an ex-prisoner with a harshness he
does not intend, but in most cases the persecution only exists in the
imagination of its subject. Few of us see all things as they are. We
are influenced by our beliefs quite apart from their foundation in
fact, and this is shown in all our actions. We see men believing in
others in spite of evidence which we think ought to undeceive them;
and people have been known to get married under a quite mistaken
estimate of each other’s character.
So long as the discharged prisoner believes that the world is against
him, that the hand of the representative of the law is raised to
oppress him, his actions will be influenced by that belief; and he
may be driven to despair as a consequence. I do not think that
policemen generally have any ill-feeling towards offenders; but
officially there is no encouragement for any personal feeling on their
part, good or bad. Theirs is an unenviable position.
We make no real attempt to investigate the cause of wrongdoing
and to prevent crime by a rational method. Should a policeman
interfere before an offence has been committed, the motive of his
interference will as often as not be misinterpreted and he will be
denounced as a busybody. In practice we encourage him to believe
that it is his main duty to arrest offenders and he does his best to
discharge this duty. It is too much to expect that between him and
those whom he is set to hunt there can be any likelihood of mutual
regard. As enemies each may have a respect for the other, but
friendship and friendly help are out of the question. Unfortunately
this fact has been left out of account in some recent proposals for
the prevention of crime and the reformation of the offender.
In connection with all the prisons there are discharged prisoners’ aid
societies, which seek to help those whose sentences have expired.
The number of these societies is increasing; but in Glasgow,
praiseworthy as are their efforts, they are quite unable to undertake
the work that requires to be done. In practice the societies mainly
consist of their officials, and these are few and hardworking. They
try to get situations for discharged prisoners and to influence them
towards a better way of living. Sometimes their efforts meet with
success, but they have far too much to do. Their resources are
small, and they are hampered by want of funds, but more by want
of helpers. They struggle on valiantly in spite of discouragement,
and do what lies in their power to prevent those with whom they
come in contact from becoming worse than they otherwise would
be.
When a prisoner is liberated it is not always an easy matter for him
to find work. The fact of his having been in prison is not a
recommendation to anyone who would employ him. When work is
found for him by the agents of one of the societies which help
discharged prisoners, his position may be a somewhat difficult one.
It is not every place where he can be employed without objection on
the part of his fellow-workers. As men they recognise the need for
charity and tolerance towards their neighbours, but prison has such
an evil sound to them that they are prejudiced against the person
who has been there. When this prejudice is overcome there is
usually a reaction in the ex-prisoner’s favour, resulting in conduct
towards him that may be as embarrassing in its way as any
springing from the prejudice against him. At the best he is liable to
be placed in an atmosphere of suspicion that does not help him to
do well. The consciousness that he has been degraded is harmful to
his sense of self-respect, and altogether it is not easy for him to find
suitable companionship. Wisdom would counsel him to avoid the
company of those who have been associated with him in the conduct
that led to his fall, but the counsels of wisdom are not always easy
to follow.
There are very many who are willing to give assistance to a man
who seeks to turn over a new leaf, but they expect to direct him as
to what shall be written on the next page. If censure and avoidance
may irritate and hurt a man who has been convicted of wrongdoing,
patronage may raise a spirit of opposition in him. He does not want
to be looked down upon, whether with contempt or with
compassion. Of course, he ought to be chastened by his affliction;
he ought to be repentant and submissive; he ought to do what he is
told; but it is not what ought to be that requires consideration if we
would help him to do better, but what is. In spite of their vicious
acts, it is never an evidence of wisdom to assume that vicious
people are greater fools than others. That they behave foolishly,
from the standpoint of their own and our interest, is quite true, and
so apparent that it needs no emphasis. The question is, Do we, who
are so much wiser than they, show that wisdom in our treatment of
them? and the answer, evidenced by the result of our attitude
towards them, furnishes no strong testimony in our favour.
When a man has gone wrong it may be generally assumed that
there is something in him that has made him unfit to resist the
temptations incident to his position. If this assumption be correct it
follows that we are not warranted in expecting from him the same
power of resistance as others have shown. We are not justified in
assuming that with proper assistance his character and powers may
not improve, but it is hardly reasonable to expect conduct from him
that would be more saintly than our own; and a great many
disappointments are suffered by earnest people who seek to lift up
the fallen, simply because they have expected too much. When
efforts to help a man result in failure it is a safe working rule to
assume that the fault is at least as much in the nature of the means
employed as in the man. They may have been very good means, but
they have not been applicable in the case; which is just to say that
the result is the test of their suitability. This is all so obvious that in
practice it is disregarded, and we persist in the foolish assumption
that people on whom our patent pills fail to act are incorrigible;
though the fact is that the offender is no more incorrigible than the
reformer, and is sometimes not so stupid.
The position of the man who has been in prison is not so bad as that
of the woman who has been there. There can be no question that
women less frequently break the laws than men. This may or may
not be evidence of superior virtue on the part of women, but the
fact itself makes the position of the woman who has fallen more
difficult to retrieve. She is more conspicuous than the male offender,
if only because there are fewer of her kind, and the attitude of
women towards her is less tolerant than the attitude of men, either
towards her or towards those of their own sex who have offended.
Accordingly, when a woman once loses her reputation she is more
liable than a man to accept the position and to sink under her
disgrace; so that the fallen woman is regarded by many as the most
degraded of beings, and her rescue has a fascination for those who
seek to aid the worst. This conception is absurd, as everyone knows
who has studied the subject with open eyes, but the question is one
that cannot be faithfully dealt with here. The economic position of
the woman who has broken away from the standards set by the law
need not be, and often is not, worse than that she held before her
revolt. It all depends on what she was and how she has rebelled.
Vice as little as virtue determines the economic position of those
who are subject to it. The transgressor by her transgression is cut
off from her class, and she is in danger of failing to gain a footing in
any other. She may, and in the majority of cases does, glide out of
her folly as she has slipped into it; but when she is publicly branded
her chances of recovery are less than those of a man. The attitude
of men towards her may be insolent, but it is rarely so brutal as that
of women; and it is no uncommon thing to find that the most
effective help towards the restoration of a woman has been given by
those among her male friends whose character would least bear
scrutiny by a censor of morals.
The attitude of her sex towards the woman who is down is generally
one of hostility. Whether something of the instinct of self-
preservation inspires this need not be here discussed; but it is
abundantly clear that the woman whose fall has been publicly
recognised cannot hope to resume anything like her old place, even
if she were willing to seek it. Her recognition as a respectable
woman is too frequently made contingent on her acceptance of a
form of religion that enables her past to be always referred to, and
herself held up as a brand plucked from the burning. In her attitude
towards women she is affected by this knowledge, and their appeal
to her loses in effect because of it. There is nothing more difficult
than the treatment of these women. The prejudice against them is
so strong that it is only here and there a family is willing to take in
and look after one of them.
Attempts are made to influence and direct such women as have no
friends, by placing them in homes. No doubt the inmates are much
better there than they would be if turned on the streets or living in
common lodging-houses; but they do not commend themselves to
those whom it is sought to rescue; for the majority of them will say
quite frankly that it is “not good enough.” They prefer to struggle
along as best they may rather than submit to the life offered them.
It always appears ungracious to criticise the work of those who are
earnestly engaged in trying to help others, but it is fair that the view
of those they seek to help should be presented. Their view may be a
wrong one, but until it is altered it will affect their conduct; and it
cannot be too emphatically insisted on that the opinions of those
whom we seek to help should be considered, and when possible
acted upon, if it is hoped to render effective aid. The first objection a
girl makes to entering a rescue home is that she must bind herself to
remain there for a prolonged period. She does not regard the home
as a desirable place of residence, but as a step towards restoration
to a decent position in the community. She objects to give her work
for twelve months, say, getting no other pay than her board,
clothing, and lodging, unless she remains in the institution for that
time. She claims that she might as well be in prison. The girl is not
concerned with the question whether the home pays others or not;
she is concerned with the fact that it does not pay her.
Loss of reputation hinders a girl from getting a situation, even when
she is willing to drop her way of living and revert to steady work.
People who pay well quite naturally prefer not to make an
experiment and seek to have their money’s worth, which implies not
only an efficient, but a steady and reliable worker. The situations
open to the penitent, therefore, are those which are worst paid.
When she gains a character she may obtain more remunerative
occupation elsewhere. She recognises that on account of her bad
reputation she has to do more work for less money, but she does
not so readily admit that it is just that it should be so. She thinks
that it is one thing for an ordinary person to take advantage of her
needs and to underpay her, while it is quite another thing for a
Christian institution to keep her working for insufficient wages. In
the home she has as hard work and almost as little liberty as she
would have were she in prison. Her associates are girls like herself,
with whom she can converse on a basis of equality and discourse on
life from a similar standpoint. On the other hand, she is preached to,
patronised by visitors, entertained in a very proper manner, and
taught in a thousand indirect ways that she is different from them. If
her associates do not help her to forget her past, neither do her
teachers. They want to be kind, and try to be considerate; the effort
is obvious. In a gentle way they may tell the girls what they think of
them and how much need there is for their reformation, and they do
not seem to see that they would come more closely in contact with
those they seek to help if they would assume the things they
express by word and attitude, and try to draw the girls out. The
defect in the teacher is too often a habit of talking at his pupils. The
girls are there to learn; the visitors to teach. Are they? What do the
girls learn, and what do the visitors teach? That we are all sinners
and our position a perilous one; that some of us have been found
out and that the penalty should be accepted humbly as being for our
good, and so on. If the formula is somewhat stereotyped that is not
my fault. The girls who appear to submit most patiently are naturally
regarded as most hopeful. What they think about it all does not
appear to be considered of much importance. They are wrong or
they would not be there; and yet a girl may make a mess of her life
in one direction, and be none the less qualified to give a shrewd and
useful opinion on the causes of her failure. If those who seek to
teach them had less faith in their own doctrine and more desire to
learn, they would become less ignorant and would teach to better
purpose. Here and there some know this, and acting on the
knowledge, are more successful than others who are equally pious,
equally well-intentioned, but less well-informed.
One quite recognises that it cannot be charged against the majority
of these institutions that they make money by the girls. They are
often carried on at a financial loss, for the cost is considerable; but
reformatory work cannot be conducted on a commercial basis. It is
in the nature of things that it should not pay its way in the narrow
sense. The cost of adequate supervision prevents this. But to charge
the cost of attempts at their reformation to the girls is to inflict at
least an apparent injustice on them that is apt to rankle in their
minds, and to drive away a number who would otherwise be helped
—helped at a pecuniary loss to the home, but at a great benefit to
the community. After all, they are earning their own living by their
work. What they fail to do is to earn a living for those who govern
them. In exchange for their work they are not permitted to spend
their earnings as they please, but as it pleases those who have
undertaken to look after them. There may be something to be said
for the opinion that if one set of persons seek to direct the lives of
another they should be prepared to pay for the privilege; but this
subject of charity is one that needs examination. Some people have
very quaint ideas regarding it. I remember a decent woman who
rather prided herself on her goodness. Her husband had a small
business, and she occasionally requisitioned the services of his
younger apprentices for assistance at cleaning time. On such an
afternoon a newsboy coming to the door, she got a Citizen from him,
gave him a penny, and received back the halfpenny of change. When
he had gone she remarked to one of the apprentices—a boy with a
genius for saying the right thing in the wrong place—“Puir boy, I just
take the paper from him for charity.” To which he replied, “Aye, but
ye took the halfpenny back!” There was something to be said for
both views, but the boy had the last word, and he soon found that
his criticism had borne fruit; he was dismissed.
In the home there is more of a religious atmosphere and less
mechanical routine than in prison; but the religious atmosphere is as
much objected to by many of the girls as the mechanical routine.
Both may be good for them from the standpoint of the theorist, but
neither seems to result in the effect desired. In the prison there are
fewer lectures and fewer visits to the inmates than in the home, and
the life is more monotonous, but in the prison there is less
opportunity for contamination. In both places the old and degraded,
the young and the ignorant, may be confined, but in the prison they
are separated.
It is quite a mistake to imagine that the vice and degradation—that
the state of morals—of a person can be estimated by her age and
the number of her convictions. The old hand need not be so morally
corrupt as the younger, though her experiences may have been
more numerous and varied. A common statement of those who have
been inmates of homes is that what they did not know when they
went in they learned before they came out, and certainly they have
opportunities of communicating their experiences and relating their
adventures while they are in a home that they do not have while
they are in prison. This is a thing that cannot be prevented so long
as people live together. That many have been restored after passing
through the homes is undoubtedly the case, but it does not follow
that their restoration was due to their experience there. That many
have not been improved, but have been the worse for their
residence there, is not at all to be wondered at. Where a religious
atmosphere has affected them favourably the disadvantages
inherent to the establishment have been overcome. Where it has
failed to effect a change in them for good the other associations
tend to confirm them in evil.
What effect, then, has imprisonment on those who undergo it? It
usually improves their health physically, but impairs their mental
capacity. The simple life favours the former; separation and
destruction of the sense of initiative favour the latter. Many do not
return after a first experience, and it is assumed that they have been
deterred from wrongdoing by it; but there is absolutely no ground
for this assumption. It may be justified in some cases, but in others
there is no reason to suppose that the offender would have repeated
his offence, even though he had never been sent to prison for it.
Imperfectly as probation of offenders is worked, it has shown this.
Indeed, the very imperfection of the method has shown it the more
strongly, for so far from the offender having been taken away from
the conditions which incited him to commit his transgression, he has
been sent back to them, and in many cases has not again offended.
It is not right to make assumptions when there is opportunity of
examining the facts; and no enquiry has been made as to the effect
of imprisonment in deterring those who have been in prison and
have not returned for repeating their offence. A great many do
return, and that is positive evidence that their imprisonment has not
had a deterrent effect on them. Why do they return? In some cases
they have found that prison is not such a horrible place after all, and
that though the confinement is irksome the time passes; and at the
expiry of their sentence they may do what they like. Many of them
have to work hard and long to earn a living when outside, and they
learn that they can pick up a living at less cost and have a better
time, if they take the risk of being shut up now and again. They
have been cut off from their habits, which may not have been a bad
thing, and have acquired other habits which do not help them when
they are liberated. They have been officially marked with disgrace,
and to that extent rendered less able to secure employment and
good company. They have been taught to be respectful and
obedient, but they have lost, in a corresponding degree to their
improvement in manners, their power to act for themselves. In some
respects they are better, in others worse, than they were when they
were taken in hand; and on the balance there is a distinct loss.
Recent attempts at reformation have not taken into account the root
causes of failure, and they fail to recognise that the longer a person
is cut off from the main current of life in the community the less he
is fitted to return to it.

CHAPTER VI

THE INEBRIATE HOME


The need to find out why people do wrong before
attempting to cure them—Enquiries as to inebriety
—The inebriates—Official utterances—Cost and
results—The grievance of the unreformed—The
time limit of cure—The causes of failure—The
fostering of old associations—The prospect of the
future spree—The institution habit.

I T cannot be seriously contended that our methods of dealing with


offenders make for their reform. It may be that some of those
who do not return to prison have been checked in their career by
the treatment they have received, but as a matter of fact, there are
a great many people sent to prison who ought never to have been
there at all. In my opinion it is beyond dispute that our methods
result in the making of criminals; that in the majority of cases
imprisonment not only does no good, but does positive and serious
harm. It should not be forgotten, however, that there is no ground
for supposing that the prison system is intended to reform those
who come within its operation. It keeps them off the street for a
time and prevents them from annoying those who are at liberty; but
this cannot be done without financial cost to the community, and it is
only done at a very serious loss in other respects. The same amount
of money spent in helping them to do well as it costs to imprison
them for doing ill, would prevent many of them from offending; but
before this could be done more would require to be known regarding
the individuals than the mere fact that they have offended against
one or other of our laws.
It is necessary not only to find out where and how the criminal has
gone wrong, but also where and why we have gone wrong in our
method of treating him. Profitable as it would be, no serious attempt
has been made to do this. The most that is done is to admit the
inefficacy of prison treatment and to devise some theoretical
improvement on it. It seems easier for some people to reason in
vacuo—in their own heads—than to examine the facts and face the
consequences. Of late years the public has permitted one institution
after another to be foisted on it at the bidding of people who have
not shown even the most elementary knowledge of the subject with
which they were dealing, and of faddists who want to regulate other
men’s lives by their own. Their opinion of the offender may be
interesting and it may have a value different from what they place
upon it; but it is not nearly as interesting, as helpful, or as valuable
as the offender’s own opinion of the cause of his fall and of his
needs.
The imprisonment and reimprisonment of the habitual offender had
become a scandal. It was recognised that inebriety made men and
women a danger and a nuisance to the family and their neighbours,
but no greater a nuisance than the system by which we dealt with
them. Everybody agreed that imprisonment made them no better. It
made them abstainers only for the time they were in custody, but it
did nothing to destroy the desire for drink. So an Act of Parliament
was passed to enable them to be placed in an institution of another
sort. If the prison failed to reform them, the Inebriate Homes have
proved a more costly, a more ghastly failure. Instead of finding out
the cause of the failure, a departmental committee, after examining
anybody but those who had been in the homes, has recommended
that further parliamentary powers should be granted to the
committees managing them and courts sending inmates to them.
The rational method of procedure would have been for intelligent
and impartial persons to examine those cases which had been
improved, and to estimate how far the improvement was due to the
treatment received. This would not have been a difficult task, for the
cases were few; and having accomplished it, it would have been
equally profitable to examine the many cases of failure and to seek
the causes of that failure. It is much easier, however, to collect the
opinions of officials, of philanthropists, of those who are interested
in prescribing for the conduct of others—in short, of people who are
called authorities on a given subject, because nobody has been bold
enough to challenge them—than to obtain the confidence and open
the mouths of those whose wrongdoing it is sought to correct. It is a
grotesque statement that the Inebriate Home failed because the
wrong people were sent to it; also it is not true. It would be nearer
the mark to say that the home failed because it was not suited for
the treatment of inebriates. For after all, the very people for whom it
was designed to afford treatment were among those sent there.
The patients chosen for treatment in the Inebriate Home were
carefully selected by a physician experienced in the treatment of
mental diseases. Some of them were mentally affected as a
consequence of their drunkenness, and there is room for supposing
that some took to drink partly on account of a mental defect; but
inebriety is not a physical disease, it is not a mental disease,
although it may have some relationship to physical and mental
diseases. It was because of its being a social disorder that the State
undertook to consider these persons. This being so, each case could
only be rationally considered in relation to the social condition of the
inebriate. Information about the state of their various internal organs
might be useful, but it could never replace in importance or interest
information as to their social condition.
The treatment failed because it was not adapted to the persons to
be treated, but was adapted to the state of mind of those who, on
the strength either of an academic qualification, or a belief in their
fitness to judge people who are of a lower social condition, had
prescribed a method without any real knowledge of the persons to
whom they sought to apply it. The public pays too much attention to
the utterances of those in authority, and it is difficult to avoid the
habit of mistaking for knowledge what is only a different kind of
ignorance from our own. A thing is not true because somebody says
it; it may be true in spite of that; but it would repay the trouble were
official utterances more closely scrutinised than they are. Zeal,
honesty, integrity, may be present in the official, and he may be a
very talented man as well, and yet he may lead matters into a sad
mess. The less he is questioned, the more he is suffered to go on
unchecked, the worse for him and for those whose servant he is.
The good servant may become a very bad master. Then all official
persons are not equally able. If a man has not wit, it is not likely to
be developed in him by giving him a title or a uniform. If he has not
much wisdom, he is not likely to become less foolish even though
you place him in the seat of Solomon. The fact that a man holds a
position is not proof of his fitness to fill it; and respect for an office
makes it all the more incumbent on honest men to scrutinise and
criticise the actions of the person who occupies it. Loyalty to the
public service is too often confused with servility to those in the
upper ranks, resulting in something very like a conspiracy to magnify
their importance (which would be a small matter), and to induce the
public to attach an undue weight to what they say, though their
statements may appear foolish enough. All this is quite heterodox
doctrine, and in practice will not tend to make a man’s path smooth;
but the orthodox method of assuming that the higher in authority a
person is, the abler and wiser he must be, has not resulted so
satisfactorily that it should escape challenge.
The official reports of Girgenti Inebriate Home were a great deal
more satisfactory than the results, and the home might have been in
existence yet if the representatives of the public had not informed
themselves of the real state of affairs. A few cures are put to its
credit at a calamitous expense. The cost of keeping a woman there
amounted to between twenty-five and thirty shillings per week, and
the odds were proved to be against her being reformed after three
years’ treatment. In other words, the public were guaranteed that all
persons sent to the home could be kept sober at a cost of from
sixty-five to eighty pounds each per year, but they had no reason to
believe that when this payment ceased on their part the patient
would take her place in the community and remain a sober citizen. If
she was not made better, did she become worse as a result of her
treatment there? In some respects she did. You cannot meddle with
the lives of others without result, for it is impossible to leave them as
you find them.
I remember being visited one morning by a woman who had left the
home after a three years’ stay there. She had been drinking before
she called on me, and she had some complaints to make regarding
her treatment there. The complaints were trifling in character, and
were more in the nature of gossip than anything else. I told her that
she had cost the community some £200 to keep her during the last
three years, and they seemed to have made a bad bargain. I
advised her to think a little less of her grievances and a little more of
the comfort of her neighbours, and dismissed her with the usual
censure and advice; but she had a case against the State, although
she was not able to express it clearly. I would put it for her thus:
“When you interfered with my life I had fallen into the habit of
drinking, but in the main I earned my own living and meddled very
little with others to their annoyance. I had my friends, whom your
judgment might not approve, but between them and myself there
were common ties. We sympathised with each other and helped
each other. You undertook to reform my life, to break me of my bad
habits, to make me more fit to earn my living without offending
against your laws. You have ruled and governed me for three years.
You put me in a home where my life was regulated for me; you gave
me as companions people with whom I had never associated before;
you compelled me to live in their company; you taught me nothing
that I find of any use to me outside; you kept me from drinking. It
may have been a poor pleasure, but it was the only one I had. You
did not take the taste for it away, and you have given me nothing to
replace it; and now I am three years older, and you turn me loose on
the streets of the city to which I belong, and in which I am now
through your action very much a stranger, and invite me to work for
my living in competition with others. I could work and did work
before you meddled with me; I could work yet, but I must have
something to fill my life as well as work, and I have taken to drink
again, because it is the only thing I know that meets the need I feel.
I am worse off than I was before you started to reform me. Then I
had friends, now I am alone; for they have gone their own way:
some to death, all of them from me. There is nobody from whom I
can have the sympathy and the help I once had. My friends had
their faults and they knew mine; that was why we were friends. All
you can offer me is patronage, advice, direction from people whom I
don’t know and who don’t know me. The one thing that I want,
which is fellowship, I have not got. You have taught me to depend
on others. You have made me obey your rules, and now you set me
free to make rules for myself, and leave me to drift back into the
place where I was; to face the same difficulties, the same
temptations, without the companionship of those who had grown
into my life. You have taken three years from my life and you have
given me nothing for it. Give me back my life or justify your
interference with it by fitting me to become a better citizen than I
was.”
This is something like what the woman appeared to feel and tried to
say, and there is really no answer to it. It is not a wise proceeding to
treat the lives of men and women as toys with which we can play,
and throw them aside without practical regard for consequences
when we are tired of the game. If we do not direct them, they will
direct themselves, and the less fitted they are to do so the worse for
us. I remember one woman who was an inmate of a home, but who
had been employed on a farm outside under licence. Her behaviour
was excellent; she was a good worker, although she had had over a
hundred convictions for drunkenness before her admission to the
home. She always had been a good worker in the intervals between
the drinks. She conformed to the terms of the licence, whatever
these were, and seemed to be a reformed character. I suggested to
her that it was perfectly clear that, though she could not resist the
temptations incident to life in the slums of a great city, she might
continue for an indefinite period to live a useful life in the country.
She replied, “As soon as my three years are up I am going back to
the town,” and she kept her promise, with the result that she went
back to her drinking. In her case it was proved that she could
behave for a long period when the only alternative presented to a
regulated life outside an institution was a more rigidly regulated life
inside an institution. She preferred the outside farm to the home,
but she preferred the streets of the city to either, and her case raises
the question whether it is advisable to withdraw all control from
those like her. She did not require to be continually overlooked by
officials in order that she should conform to the law. Her life was left
under the inspection of the inhabitants of the district in which she
worked, and it is quite conceivable that she might have been
working there yet, if she had not known that the reward of
restraining herself would be not so much a change in character, as
freedom from any supervision when a fixed term had expired.
The cause of the failure of the Inebriate Home did not lie in the
character of the inmates or of the officials who were placed over
them, but in the defect inherent in all institutions; the fact that the
manner of living in them differs essentially from anything that
obtains outside. They are all founded more or less on the military
model, and the military model and the industrial model are different.
Far more than most of us suspect we are the creatures of habit:—
often of habit acquired slowly, gradually, and unconsciously. To
remove ourselves from one place to another implies the breaking off
from some habits, but it also implies the formation of others. It did
not need the experience of the Inebriate Home to let us know that
men might be removed from the opportunity of drinking for long
periods and, on return to their former conditions, resume the habit.
Years of imprisonment, where teetotalism is rigidly enforced and
where the diet is of a non-stimulating character, did not make the
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!

ebookname.com

You might also like