100% found this document useful (1 vote)
4 views

Learn Objectoriented Java The Hard Way Graham Mitchell instant download

Learn Object-Oriented Java the Hard Way by Graham Mitchell is designed for beginners who have some prior programming experience, particularly in Java or similar languages. The book emphasizes hands-on learning through small programming exercises, covering various object-oriented concepts and Java syntax. It aims to bridge the gap for learners who may struggle with more advanced programming materials written by experienced developers.

Uploaded by

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

Learn Objectoriented Java The Hard Way Graham Mitchell instant download

Learn Object-Oriented Java the Hard Way by Graham Mitchell is designed for beginners who have some prior programming experience, particularly in Java or similar languages. The book emphasizes hands-on learning through small programming exercises, covering various object-oriented concepts and Java syntax. It aims to bridge the gap for learners who may struggle with more advanced programming materials written by experienced developers.

Uploaded by

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

Learn Objectoriented Java The Hard Way Graham

Mitchell download

https://ebookbell.com/product/learn-objectoriented-java-the-hard-
way-graham-mitchell-48927976

Explore and download more ebooks at ebookbell.com


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

The Java Workshop Learn Objectoriented Programming And Kickstart Your


Career In Software Development David Cuartielles

https://ebookbell.com/product/the-java-workshop-learn-objectoriented-
programming-and-kickstart-your-career-in-software-development-david-
cuartielles-46712648

Java Programming For Beginners Improve Your Software Engineering


Skills By Learning To Code Using An Objectoriented Program Learn About
The Virtual Machine Javascript And Machine Code 2022 Vergil Silva

https://ebookbell.com/product/java-programming-for-beginners-improve-
your-software-engineering-skills-by-learning-to-code-using-an-
objectoriented-program-learn-about-the-virtual-machine-javascript-and-
machine-code-2022-vergil-silva-46408466

Interactive Objectoriented Programming In Java Learn And Test Your


Programming Skills 2nd Edition 2nd Edition Vaskaran Sarcar

https://ebookbell.com/product/interactive-objectoriented-programming-
in-java-learn-and-test-your-programming-skills-2nd-edition-2nd-
edition-vaskaran-sarcar-50195476

Interactive Object Oriented Programming In Java Learn And Test Your


Skills 1st Edition Vaskaran Sarcar Auth

https://ebookbell.com/product/interactive-object-oriented-programming-
in-java-learn-and-test-your-skills-1st-edition-vaskaran-sarcar-
auth-5696030
Interactive Objectoriented Programming In Java Learn And Test Your
Programming Skills Vaskaran Sarcar

https://ebookbell.com/product/interactive-objectoriented-programming-
in-java-learn-and-test-your-programming-skills-vaskaran-
sarcar-232010682

A Software Engineer Learns Java And Object Orientated Programming


Cameron

https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-cameron-43039484

A Software Engineer Learns Java And Object Orientated Programming 1st


Dane Cameron

https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-1st-dane-cameron-6769022

A Software Engineer Learns Java And Object Orientated Programming Dane


Cameron

https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-dane-cameron-43187710

A Software Engineer Learns Java And Object Orientated Programming


Cameron

https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-cameron-22783254
Learn Object-Oriented Java the Hard Way
Graham Mitchell
This book is for sale at http://leanpub.com/javahard2

This version was published on 2016-08-14

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

© 2015 - 2016 Graham Mitchell


Also By Graham Mitchell
Learn Java the Hard Way
Contents

Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Preface: Learning by Doing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

Introduction: Object-Oriented Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

Exercise 0: The Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Exercise 1: Working With Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Exercise 2: Creating Your Own Single Objects . . . . . . . . . . . . . . . . . . . . . . . . . 23

Exercise 3: Defining Objects in Separate Files . . . . . . . . . . . . . . . . . . . . . . . . . 26

Exercise 4: Fields in an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Exercise 5: Programming Paradigms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Exercise 6: Accessing Fields in Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Exercise 7: Encapsulation and Automated Testing . . . . . . . . . . . . . . . . . . . . . . . 42

Exercise 8: Failure to Encapsulate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Exercise 9: Private Fields and Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Exercise 10: Automated Testing with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 56

Exercise 11: Public vs Private vs Unspecified . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Exercise 12: Reviewing Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Exercise 13: Default Values for Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Exercise 14: toString and this . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Exercise 15: Noughts and Crosses / Extreme Testing . . . . . . . . . . . . . . . . . . . . . 73

Exercise 16: Introduction to ArrayLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84


CONTENTS

Exercise 17: Word Counter Using an ArrayList . . . . . . . . . . . . . . . . . . . . . . . . 89

Exercise 18: Primitive Variables in Memory . . . . . . . . . . . . . . . . . . . . . . . . . . 92

Exercise 19: Reference Variables in Memory . . . . . . . . . . . . . . . . . . . . . . . . . . 96

Exercise 20: Lists of Primitive Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Exercise 21: Generics vs. Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

Exercise 22: Object-Oriented Design and Efficiency . . . . . . . . . . . . . . . . . . . . . . 112

Exercise 23: Writing a Silly Class with Generics . . . . . . . . . . . . . . . . . . . . . . . . 118

Exercise 24: Writing a Useful Class with Generics . . . . . . . . . . . . . . . . . . . . . . . 123

Exercise 25: Sorting and Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

Exercise 26: Sorting Speeds - Primitives vs Objects . . . . . . . . . . . . . . . . . . . . . . 143

Exercise 27: Static Variables and Static Methods . . . . . . . . . . . . . . . . . . . . . . . . 149

Exercise 28: Popular Static Methods in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 153

Exercise 29: Importing Static Class Members . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Exercise 30: References as Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Exercise 31: Java Strings Are Immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

Exercise 32: Parameters vs Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

Exercise 33: Basic Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

Exercise 34: How Fields Are Inherited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

Exercise 35: “Useful” Inheritance - A Game Board . . . . . . . . . . . . . . . . . . . . . . . 180

Exercise 36: A Game Called Breakthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Exercise 37: Two Kinds of Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

Exercise 38: Implementing Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

Exercise 39: The Comparable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

Exercise 40: List and Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

Exercise 41: Implementing Several Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . 220


CONTENTS

Exercise 42: DropGame and Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Exercise 43: Abstract Classes and Final Methods . . . . . . . . . . . . . . . . . . . . . . . 232

Exercise 44: Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

Exercise 45: Creating a JAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240

Exercise 46: A Simple Graphical Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244

Exercise 47: An Interactive Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Exercise 48: Using (F)XML to Define Your Interface . . . . . . . . . . . . . . . . . . . . . . 254

Exercise 49: Canvas Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

Exercise 50: Getting Mouse Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

Exercise 51: More Complex Mouse Interaction . . . . . . . . . . . . . . . . . . . . . . . . . 267

Exercise 52: Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

Exercise 53: Handling Keypress Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

Exercise 54: Graphical Noughts and Crosses . . . . . . . . . . . . . . . . . . . . . . . . . . 283

Exercise 55: Graphical Drop Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290

Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297


Acknowledgements
To God, who gives me the ability to create.
To Deanna, who believed I could finish this even when I wasn’t sure.
To the hundreds of people who purchased my first book; this second book wouldn’t exist without
you!
And to Jesus, who teaches me grace and humility every day. May I depend on Him more and more
each day.
Preface: Learning by Doing
I have been teaching beginners how to code for the better part of two decades. More than 2,000
students have taken my classes and left knowing how to write simple programs that work. Some
learned how to do only a little and others gained incredible skill over the course of just a few years.
I have plenty of students who are exceptional but most of my students are regular kids with no
experience and no particular aptitude for programming. This book is written for regular people like
them.
Most programming books and tutorials online are written by people with great natural ability and
very little experience with real beginners. Their books often cover far too much material far too
quickly and overestimate what true beginners can understand.
If you have a lot of experience or extremely high aptitude, you can learn to code from almost any
source. I sometimes read comments like “I taught my 9-year-old daughter to code, and she made her
first Android app six weeks later!” If you are the child prodigy, this book is not written for you.
I have also come to believe that there is no substitute for writing lots of small programs. So that’s
what you will do in this book. You will type in small programs and run them.
“The best way to learn is to do.” – P.R. Halmos
Introduction: Object-Oriented Java
Java is an object-oriented programming language. My first book covered all the basic syntax of the
Java language, but avoided all the object-oriented parts. This book covers the rest.
If you have never programmed before in any language, this book is probably not for you. You need
some experience in a similar language before you will be able to make it through this book. If you
already know the basics of Java or another language like C, C++, C# or Javascript, you will be okay.
If you only know a very different language like Python or Ruby then you’ll have a little catching up
to do.
If you get lost trying to follow the code in exercise 1, then you should probably go back and work
through a simpler book before trying this one.

What You Will Learn


• How to install the Java compiler and a text editor
• How to work with Java objects and create your own classes
• Fields and instance variables
• Methods and Parameters
• Constructors
• Reference Variables vs Primitives
• Generics and Casting
• Inheritance
• Interfaces
• Abstract Classes and Methods
• Packages
• How to create JAR files
• Graphical User Interfaces in JavaFX
• Mouse and Keyboard Input in GUIs
• Testing and Efficiency
• Algorithmic Complexity and Big-O Notation
• ArrayLists
• Sorting
Introduction: Object-Oriented Java iv

…and more!
In the final chapter you’ll write a graphical version of a popular checker-dropping game and be able
to package that up to send to others.
All the examples in this book will work in version 1.8 of Java or any newer version. If you omit the
last few chapters on JavaFX, most of the code will work in Java version 1.6 or later.

What You Will Not Learn


• How to compile and run Java programs in a terminal
• The basics of Java
• How to make an Android app
• Specifics of different “versions” of Java
• Javascript

Create, compile & run


If you have written some Java before but you have always used an IDE, you should learn how
to write your code in a simple text editor and how to compile your code from a terminal. My
first book has an entire chapter¹ on it which is free to read online, so work through that first
if you need to.

No basics
If you don’t already know how to create variables and write if statements, loops and functions
in Java, then you should learn that before trying to work through this book.

No Android
Android apps are pretty complex, and if you’re a beginner, an app is way beyond your ability.
Nothing in this book will hurt your chances of making an app, though, and the kinder, gentler
pace may keep you going when other books would frustrate you into quitting.

No specific version
I will not cover anything about the differences between Java SE 7 and Java SE 8, for example.
If you care about the difference, then this book is not for you.
Except for the last few graphics chapters, I will also not cover anything that was only recently
added to Java. This book is for learning the basics of object-oriented programming and nothing
has changed about the basics of Java in many years.

No Javascript
“Javascript” is the name of a programming language and “Java” is also the name of a
programming language. These two languages have nothing to do with each other. They are
completely unrelated.
¹https://learnjavathehardway.org/book/ex01.html
Introduction: Object-Oriented Java v

I hope to write more books after this one. My third book will cover making a simple Android app,
assuming you have finished working through the first two books.

How to Use This Book


Although I have provided a zipfile containing the source code for all the exercises in the book, you
should type them in.
For each exercise, type in the code. Yourself, by hand. How are you going to learn otherwise? None
of my former students ever became great at programming by merely reading others’ code.
Work the Study Drills. Then watch the Study Drill videos (if you have them) to compare your
solutions to mine. And by the end you will be able to code, at least a little.

License
Some chapters of this book are made available free to read online but you are not allowed to make
copies for others without permission.
The materials provided for download may not be copied, scanned, or duplicated, or posted to a
publicly accessible website, in whole or in part.
Educators who purchase this book and/or tutorial videos are given permission to utilize the
curriculum solely for self-study or for one-to-one, face-to-face tutoring of a single student. Large-
group teaching of this curriculum requires a site license.
Unless otherwise stated, all content is copyright 2015-2016 Graham Mitchell.
Exercise 0: The Setup
This exercise has no code but do not skip it. It will help you to get a decent text editor installed
and to install the Java Development Kit (JDK). If you do not do both of these things, you will not be
able to do any of the other exercises in the book. You should follow these instructions as exactly as
possible.

This exercise requires you to do things in a terminal window (also called a “shell”, “console”
or “command prompt”. If you have no experience with a terminal, then you might need to
go learn that first.
I’ll tell you all the commands to type, but if you’re interested in more detail you might
want to check out the first chapter of “Conquering the Command Line” by Mark Bates. His
book is designed for users of a “real” command line that you get on a Linux or Mac OS X
machine, but the commands will be similar if you are using PowerShell on Windows.
Read Mark’s book at conqueringthecommandline.com².

You are going to need to do three things no matter what kind of system you have:

1. Install a decent text editor for writing code.


2. Figure out how to open a terminal window so we can type commands.
3. Install the JDK (Java Development Kit).
And on Windows, you’ll need to do a fourth thing:
4. Add the JDK to the system PATH.

(The JDK commands are automatically added to the PATH on Apple computers and on Linux
computers.)
I have instructions below for Windows, then for the Mac OS, and finally for Linux. Skip down to
the operating system you prefer.

²http://conqueringthecommandline.com/book/basics
Exercise 0: The Setup 2

Windows

Installing a Decent Text Editor (Notepad++)


1. Go to notepad-plus-plus.org³ with your web browser, download the latest version of the
Notepad++ text editor, and install it. You do not need to be an administrator to do this.
2. Once Notepad++ is installed, I always run it and turn off Auto-Completion since it is bad for
beginners. (It also annoys me personally.) Open the “Settings” menu and choose “Preferences”.
Then click on “Auto-Completion” about halfway down the list on the left-hand side. Finally
uncheck the box next to “Enable auto-completion on each input” and then click the “Close”
button.
3. Finally while Notepad++ is still running I right-click on the Notepad++ button down in the
Windows taskbar area and then click “Pin this program to taskbar.” This will make it easier to
launch Notepad++ for future coding sessions.

Opening a Terminal Window (PowerShell)


1. Click the Start button to open the Start Menu. (On Windows 8 and newer, you can open the
search box directly by pressing the Windows key + S.) Start typing “powershell” in the search
box.
2. Choose “Windows PowerShell” from the list of results.
3. Right-click on the PowerShell button in the taskbar and choose “Pin this program to taskbar.”
4. In the Powershell/Terminal window, type

javac -version

You will probably get an error in red text that says something like “The term ‘javac’ is not recognized
as the name of a cmdlet….”
This just means that the JDK isn’t installed and added to the PATH, which is what we expect at this
point.

If you are using a very old version of Windows, PowerShell might not be installed. You
can do all of the exercises in this book using “Command Prompt” (cmd.exe) instead, but
the navigation commands will be different and adding the JDK to the PATH will also be
different.
I recommend trying to get PowerShell installed if you can.

³http://notepad-plus-plus.org/
Exercise 0: The Setup 3

Installing the Java Development Kit (JDK)


1. Go to Oracle’s Java SE downloads page⁴ with your web browser.
2. Click the big “Java” button on the left near the top to download the Java Platform (JDK) 8u102.
Clicking this will take you to a different page titled “Java SE Development Kit 8 Downloads.”
3. On this page you will have to accept the license agreement and then choose the “Windows
x86” version near the bottom of the list. Download the file for version 8u102 or any newer
version.
If you know for sure that you are running a 64-bit version of Windows, it is okay to download
the “Windows x64” version of the JDK. If you’re not sure, then you should download the
“x86” (a.k.a. 32-bit) version, since that version will work on both 32-bit Windows and on 64-
bit Windows.
You do not need to download the “Demos and Samples”.
4. Once downloaded, run jdk-8u102-windows-i586.exe to install it. After you click “Next
>” the very first time you will see a screen that says Install to: C:\Program Files
(x86)\Java\jdk1.8.0_102\ or something similar. Make a note of this location; you will
need it soon.
5. Just keep clicking “Next” until everything is done. Unless you really know what you’re doing
it’s probably best to just let the installer do what it wants.

Adding the JDK to the PATH


1. Now that the JDK is installed you will need to find out the exact name of the folder where it
was installed. Look on the C: drive inside the Program Files folder or the C:\Program Files
(x86) folder if you have one. You are looking for a folder called Java. Inside that is a folder
called jdk1.8.0_102 that has a folder called bin inside it. The folder name must have jdk1.8
in it; jre8 is not the same. Make sure there’s a bin folder.
2. Once you have clicked your way inside the bin folder, you can left-click up in the folder loca-
tion and it will change to something that looks like C:\Program Files (x86)\Java\jdk1.8.0_-
102\bin. You can write this down or highlight and right-click to copy it to the clipboard.
3. Once the JDK is installed and you know this location open up your terminal window
(PowerShell). In PowerShell, type this:

<<(code/set-environ-var-8u102.txt)

Put it all on one line, though. That is:


Type or paste [Environment]::SetEnvironmentVariable("Path", "$env:Path;
Don’t press ENTER yet. You can paste into PowerShell by right-clicking.
⁴http://www.oracle.com/technetwork/java/javase/downloads/index.html
Exercise 0: The Setup 4

Then type or paste the folder location from above. If you installed the x86 (32-bit) version of JDK
version 8u102, it should be
C:\Program Files (x86)\Java\jdk1.8.0_102\bin
(Still don’t press ENTER.)
Then add ", "User") at the end. Finally, press ENTER.
If you get an error then you typed something incorrectly. You can press the up arrow to get it back
and the left and right arrows to find and fix your mistake, then press ENTER again.
Once the SetEnvironmentVariable command completes without giving you an error, close the
PowerShell window by typing exit at the prompt. If you don’t close the PowerShell window
the change you just made won’t take effect.

Making Sure the JDK is Installed Correctly


1. Launch PowerShell again.
2. Type javac -version at the prompt.

javac -version

You should see a response like javac 1.8.0_102.

1. Type java -version at the prompt.

java -version

You should see a response like java version "1.8.0_102".


Make sure they both report the same version number! If not, you might have two different
(incompatible) versions of Java installed and you will have trouble completing the exercises in this
book.
If the version numbers don’t match, go into the Control Panel and Add/Remove Programs. Remove
all programs related to Java, the JDK, the JRE. Remove Eclipse if it is installed. Remove everything
Java related and start again.
However, if both commands worked and you didn’t get any errors and the version numbers did
match, then congratulations! Getting all that to work is pretty hard and you probably have what it
takes to finish the rest of the book!
Don’t move on to the next exercise yet, though! We should get used to navigating using the
command-line, since that’s how you will be running the programs you write in this book.
Exercise 0: The Setup 5

Navigation in the Command-Line (PowerShell)


You should create a new folder to put all your code in. After finishing this book, you will have at
least 100 new files and it will be better if they are all in one place.

In the following text, I will use the word “folder” and the word “directory” interchangably.
They mean the same thing. The word “directory” is much older, but ever since the 1980s
graphical operating systems have used a picture of a folder to represent a directory, so that
word is now used, too.

ls

Type ls then press ENTER. (That’s an “L” as in “list”.) This command will list the contents of the
current folder/directory.

cd Documents

The cd command means “change directory” and it will move you into the “Documents” folder so
that future commands will take effect there.
Notice that your prompt will change to show that you are now inside a new folder. For example,
when I first open PowerShell on my Windows 7 machine, my prompt is
PS C:\Users\Mitchell>

Then once I change into the “Documents” directory the prompt changes to
PS C:\Users\Mitchell\Documents>

You should type ls again once you get in there to see the contents of your Documents directory.

If you are using an older version of Windows, the folder might be called “My Documents”
instead of “Documents”. If so, you will need to put quotes around the folder name for the
cd command to work, since the name of the folder contains a space:
cd "My Documents"

mkdir javahard2
Exercise 0: The Setup 6

mkdir means “make directory” and will create a new folder in the current location. Typing ls
afterward should show you that the new directory is now there. You can call the folder something
different than “javahard2” if you want to. You will only need to create this folder once per computer.

cd javahard2

Change into the javahard2 folder. Afterward, type ls and it should list nothing. (The directory is
empty, after all.)

cd ..

This is how you use the cd command to back out one level. After you type it you will be back in
just the “Documents” directory, and your prompt should have changed to reflect that.
Issue the command to get back into the “javahard2” folder again.
Now, use the mouse to open the text editor you installed earlier. Type a sentence or something and
then save the file as test.txt. Save it into the “javahard2” folder you just created.
Go back to the terminal window and issue the ls command to see the file you just created.

If you’re feeling fancy, you won’t have to use the mouse to switch back to the terminal;
you can just press Alt + Tab on Windows or Linux or press Command + Tab on a Mac
to switch applications.
Press and hold the Alt key. Keep it pressed. Then press and release the Tab key a single
time. While still holding the Alt key, press Tab several more times until your terminal
window is selected, then let go of the Alt key to make the switch.
If you just quickly press Alt+Tab and let go of both keys right away, it usually takes
you back to the previous application. I do this a lot. When I’m in the text editor I press
Alt+Tab to get back to the terminal, then when I’m done in the terminal I press Alt+Tab
again to get back to my text editor. It’s very fast once you get used to it.

You should skip down to the bottom of this chapter and read the “Warnings for Beginners”, but
otherwise you’re done with the setup and you are ready to begin Exercise 01 on Windows! Nice job.
Exercise 0: The Setup 7

Mac OS X

I don’t own an Apple computer, so I don’t currently have a way to test these directions for
myself. I have tried to explain things, but there might be some small errors.
If you use these directions, I would appreciate any emails about things that worked or
didn’t work on your computer.

Installing a Decent Text Editor (TextWrangler)


1. Go to barebones.com⁵ with your web browser. Download the Disk Image for TextWrangler
version 5.0 or any newer version.
2. Run the disk image, then open the Appliciations Folder and drag the icon over to it as indicated.
You may have to authenticate with the administrator username and password.
3. Once installed, launch TextWrangler and add it to the dock if that doesn’t happen automati-
cally.

Opening a Terminal Window (Terminal)


1. Minimize TextWrangler and switch to Finder. Using the search (Spotlight), start searching for
“terminal”. That will open a little bash terminal.
2. Put your Terminal in your dock as well.
3. In Terminal window, type

javac -version

You should probably get an error that tells you that “javac” is an unknown command. (Feel free to
email me a screenshot of the error message so I can update this paragraph.)
This just means that the JDK isn’t installed, which is what we expect at this point.

If you are using a very old version of Mac OS X, the javac command might not give you
an error! It might just print a version number on the screen!
As long as it is version 1.5 or higher, you can do all of the exercises in this book.

Installing the Java Development Kit (JDK)


1. Go to Oracle’s Java SE downloads page⁶ with your web browser.
⁵http://www.barebones.com/products/textwrangler/
⁶http://www.oracle.com/technetwork/java/javase/downloads/index.html
Exercise 0: The Setup 8

2. Click the big “Java” button on the left near the top to download the Java Platform (JDK) 8u102.
Clicking this will take you to a different page titled “Java SE Development Kit 8 Downloads.”
3. On this page you will have to accept the license agreement and then choose the “Mac OS
X x64” version in the middle of the list. Download the file for version 8u102 or any newer
version.
You do not need to download the “Demos and Samples”.
4. Once downloaded, run jdk-8u102-macosx-x64.dmg to install it.
5. Just keep clicking “Next” until everything is done. Unless you really know what you’re doing
it’s probably best to just let the installer do what it wants.

Adding the JDK to the PATH


You get to skip this part, because the JDK installer does this for you on Apple computers. You might
need to close the terminal and open it again, though, for the change to take effect.

Making Sure the JDK is Installed Correctly


1. Launch Terminal again.
2. Type javac -version at the prompt.

javac -version

You should see a response like javac 1.8.0_102.

1. Type java -version at the prompt.

java -version

You should see a response like java version "1.8.0_102".


Make sure they both report the same version number! If not, you might have two different
(incompatible) versions of Java installed and you will have trouble completing the exercises in this
book.
If the version numbers don’t match, uninstall all programs related to Java, the JDK, the JRE. Remove
Eclipse if it is installed. Remove everything Java related and start again.
Exercise 0: The Setup 9

However, if both commands worked and you didn’t get any errors and the version numbers did
match, then congratulations! Getting all that to work is pretty hard and you probably have what it
takes to finish the rest of the book!
Don’t move on to the next exercise yet, though! We should get used to navigating using the
command-line, since that’s how you will be running the programs you write in this book.

Navigation in the Command-Line (Terminal)


You should create a new folder to put all your code in. After finishing this book, you will have at
least 100 new files and it will be better if they are all in one place.

In the following text, I will use the word “folder” and the word “directory” interchangably.
They mean the same thing. The word “directory” is much older, but ever since the 1980s
graphical operating systems have used a picture of a folder to represent a directory, so that
word is now used, too.

ls

Type ls then press ENTER. (That’s an “L” as in “list”.) This command will list the contents of the
current folder/directory.

cd Documents

The cd command means “change directory” and it will move you into the “Documents” folder so
that future commands will take effect there.
Notice that your prompt will change to show that you are now inside a new folder. For example,
when I first open Terminal, my prompt is
localhost:∼ mitchell$

Then once I change into the “Documents” directory the prompt changes to
localhost:Documents mitchell$

You should type ls again once you get in there to see the contents of your Documents directory.
Now we are ready to create the folder.

mkdir javahard2
Exercise 0: The Setup 10

mkdir means “make directory” and will create a new folder in the current location. Typing ls
afterward should show you that the new directory is now there. You can call the folder something
different than “javahard2” if you want to. You will only need to create this folder once per computer.

cd javahard2

Change into the javahard2 folder. Afterward, type ls and it should list nothing. (The directory is
empty, after all.)

cd ..

This is how you use the cd command to back out one level. After you type it you will be back in
just the “Documents” directory, and your prompt should have changed to reflect that.
Issue the command to get back into the “javahard2” folder again.
Now, use the mouse to open the text editor you installed earlier. Type a sentence or something and
then save the file as test.txt. Save it into the “javahard2” folder you just created.
Go back to the terminal window and issue the ls command to see the file you just created.

If you’re feeling fancy, you won’t have to use the mouse to switch back to the terminal;
you can just press Command + Tab on a Mac or press Alt + Tab on Windows or Linux
to switch applications.
Press and hold the Command key. Keep it pressed. Then press and release the Tab key
a single time. While still holding the Command key, press Tab several more times until
your terminal window is selected, then let go of the Command key to make the switch.
If you just quickly press Command+Tab and let go of both keys right away, it usually
takes you back to the previous application. I do this a lot. When I’m in the text editor
I press Command+Tab to get back to the terminal, then when I’m done in the terminal
I press Command+Tab again to get back to my text editor. It’s very fast once you get
used to it.

You should skip down to the bottom of this chapter and read the “Warnings for Beginners”, but
otherwise you’re done with the setup and you are ready to begin Exercise 01 on Mac OS X! Nice job.
Exercise 0: The Setup 11

Linux
There are a lot of different versions of Linux out there, so I am going to give instructions for the
latest version of Ubuntu. If you are running something else, you probably know what you are doing
well enough to figure out how to modify the directions for your setup.

Installing a Decent Text Editor (gedit)


1. On Ubuntu, gedit is already installed by default. It’s called “Text Editor”. If you search for it
in the Dash, you’ll find it with “gedit” or “text”.
If it’s not installed on your Linux distro, use your package manager to install it.
2. Make sure you can get to it easily by right-clicking on its icon in the Launcher bar and selecting
“Lock to Launcher”.
3. Run gedit so we can change some of the defaults to be better for programmers:
A. In the menu bar, open the “Edit” menu then choose “Preferences”.
B. In the “View” tab, put a check mark next to “Display line numbers”
C. Make sure there’s not a check mark next to “Enable text wrapping”
D. Switch to the “Editor” tab and change Tab width: to 4.
E. Put a check mark next to “Enable automatic indentation”

Opening a Terminal Window (Terminal)


1. Minimize your text editor and search for “Terminal” in the Dash. Other Linux distributions
may call it “GNOME Terminal”, “Konsole” or “xterm”. Any of these ought to work.
2. Lock the Terminal to the Launcher bar as well.
3. In Terminal window, type

javac -version

You should get an error message that says “The program ‘javac’ can be found in the following
packages” followed by a list of packages.
This just means that the JDK isn’t installed, which is what we expect at this point.

Installing the Java Development Kit (JDK)


1. One of the nice things about Linux is the package manager. You can manually install Oracle’s
“normal” version of Java if you want, but I always just use the OpenJDK release:
Exercise 0: The Setup 12

sudo apt-get install openjdk-8-jdk openjfx

That’s pretty much it. Everything in this book works fine using OpenJDK. (In fact, I use Linux for
most of my day-to-day work and the exercises in this book were actually written and tested using
OpenJDK!)
If, however, you’re determined to have to install something like Windows and Mac users have to,
you can download it from Oracle’s Java SE downloads page⁷.
You’re on your own for installing it, though. Seriously. Just use the version provided by your package
manager.

Adding the JDK to the PATH


You get to skip this part, because this is already done for you on Linux computers. You might need
to close the terminal and open it again, though, for the change to take effect.
However, on my computer running any Java tool prints an annoying message to the terminal
window:

Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar

This is because Eclipse doesn’t work right without this JAR file. But we aren’t going to be using
Eclipse, and this message annoys me, so you need to add a line to the end of a hidden file called
.profile. (The filename starts with a dot/period, which is why it’s hidden.)

1. Launch your text editor. Click “Open”.


2. Make sure you’re in the “Home” directory.
3. Right-click anywhere in the “Open” window and put a checkmark next to “Show Hidden
Files”.
4. Open the file called .profile.
5. Add the following line at the bottom of the file:

unset JAVA_TOOL_OPTIONS

Save the file and close it. You might want to click “Open” again and remove the checkmark next to
“Show Hidden Files”.
⁷http://www.oracle.com/technetwork/java/javase/downloads/index.html
Exercise 0: The Setup 13

Making Sure the JDK is Installed Correctly


1. Launch Terminal again.
2. Type javac -version at the prompt.

javac -version

You should see a response like javac 1.8.0_91.

1. Type java -version at the prompt.

java -version

You should see a response like openjdk version "1.8.0_91".


Make sure they both report the same version number! If not, you might have two different
(incompatible) versions of Java installed and you will have trouble completing the exercises in this
book.
If the version numbers don’t match, uninstall all programs related to Java, the JDK, the JRE. Remove
Eclipse if it is installed. Remove everything Java related and start again.
However, if both commands worked and you didn’t get any errors and the version numbers did
match, then congratulations! Getting all that to work is pretty hard and you probably have what it
takes to finish the rest of the book!
Don’t move on to the next exercise yet, though! We should get used to navigating using the
command-line, since that’s how you will be running the programs you write in this book.

Navigation in the Command-Line (Terminal)


You should create a new folder to put all your code in. After finishing this book, you will have at
least 100 new files and it will be better if they are all in one place.

In the following text, I will use the word “folder” and the word “directory” interchangably.
They mean the same thing. The word “directory” is much older, but ever since the 1980s
graphical operating systems have used a picture of a folder to represent a directory, so that
word is now used, too.
Exercise 0: The Setup 14

ls

Type ls then press ENTER. (That’s an “L” as in “list”.) This command will list the contents of the
current folder/directory.

cd Documents

The cd command means “change directory” and it will move you into the “Documents” folder so
that future commands will take effect there.
Notice that your prompt will change to show that you are now inside a new folder. For example,
when I first open Terminal, my prompt is
mitchell@localhost:∼$

Then once I change into the “Documents” directory the prompt changes to
mitchell@localhost:∼/Documents$

You should type ls again once you get in there to see the contents of your Documents directory.
Now we are ready to create the folder.

mkdir javahard2

mkdir means “make directory” and will create a new folder in the current location. Typing ls
afterward should show you that the new directory is now there. You can call the folder something
different than “javahard2” if you want to. You will only need to create this folder once per computer.

cd javahard2

Change into the javahard2 folder. Afterward, type ls and it should list nothing. (The directory is
empty, after all.)

cd ..

This is how you use the cd command to back out one level. After you type it you will be back in
just the “Documents” directory, and your prompt should have changed to reflect that.
Exercise 0: The Setup 15

Issue the command to get back into the “javahard2” folder again.
Now, use the mouse to open the text editor you installed earlier. Type a sentence or something and
then save the file as test.txt. Save it into the “javahard2” folder you just created.
Go back to the terminal window and issue the ls command to see the file you just created.

If you’re feeling fancy, you won’t have to use the mouse to switch back to the terminal;
you can just press Alt + Tab on Windows or Linux or press Command + Tab on a Mac
to switch applications.
Press and hold the Alt key. Keep it pressed. Then press and release the Tab key a single
time. While still holding the Alt key, press Tab several more times until your terminal
window is selected, then let go of the Alt key to make the switch.
If you just quickly press Alt+Tab and let go of both keys right away, it usually takes
you back to the previous application. I do this a lot. When I’m in the text editor I press
Alt+Tab to get back to the terminal, then when I’m done in the terminal I press Alt+Tab
again to get back to my text editor. It’s very fast once you get used to it.

You should read the “Warnings for Beginners” below, but otherwise you’re done with the setup and
you are ready to begin Exercise 01 on Linux! Nice job.

Warnings for Beginners


You are done with the first exercise. This exercise might have been quite hard for you depending on
your familiarity with your computer. If it was difficult and you didn’t finish it, go back and take the
time to read and study and get through it. Programming requires careful reading and attention to
detail.
If a programmer tells you to use vim or emacs or Eclipse, just say “no.” These editors are for when
you are a better programmer. All you need right now is an editor that lets you put text into a file. We
will use gedit, TextWrangler, or Notepad++ (from now on called “the text editor” or “a text editor”)
because it is simple and the same on all computers. Professional programmers use these text editors
so it’s good enough for you starting out.
A programmer will eventually tell you to use Mac OS X or Linux. If the programmer likes fonts and
typography, he’ll tell you to get a Mac OS X computer. If he likes control and has a huge beard, he’ll
tell you to install Linux. Again, use whatever computer you have right now that works. All you need
is an editor, a terminal, and the Java Development Kit.
Finally, the purpose of this setup is so you can do three things very reliably while you work on the
exercises:

• Write exercises using your text editor (gedit on Linux, TextWrangler on OSX, or Notepad++
on Windows).
Exercise 0: The Setup 16

• Run the exercises you wrote.


• Fix them when they are broken.
• Repeat.

Anything else will only confuse you, so stick to the plan.

Common Student Questions


Do I have to use this lame text editor? I want to use Eclipse!
Do not use Eclipse. Although it is a nice program it is not for beginners. It is bad for
beginners in two ways:

1. It makes you do things that you don’t need to worry about right now.
2. It does things for you that you need to learn how to do for yourself first.

So follow my instructions and use a decent text editor and a terminal window. Once
you have learned how to code you can use other tools if you want, but not now.

Can I work through this book on my tablet? Or my Chromebook?


Unfortunately not. You can’t install the Java development kit (JDK) on either of
those machines. You must have some sort of traditional computer.
Exercise 1: Working With Objects
There’s no getting away from it, Java is an object-oriented language. In the original “Learn Java the
Hard Way”, I tried to avoid the object-oriented parts of Java as much as possible, but some of them
still snuck in!
In this chapter we will look at some common patterns Java uses when creating and working with
objects, and I’ll also have a brief reminder of how to compile and execute Java programs from a
command-prompt or terminal window.
Type in the following code into a single file called WorkingWithObjects.java and put it into a folder
you can get to from the terminal window.
If some of this is unfamiliar, don’t worry about it. We’re just going to be looking at patterns, and
the details aren’t that important in this assignment. In particular, you might not have ever used
ArrayList or Random, and that’s perfectly fine.
If this code is extremely overwhelming, then you might have a problem. Maybe you don’t know
what an if statement is, or System.out.println, or you’ve never used a for loop. In that case, this
book is probably going to be too difficult for you. You should go back and work through an easier
book first and then come back here once you’re quite comfortable with the basics of Java.
Anyway, type up the code below and then I’ll remind you how to compile it from the terminal.
Remember that you shouldn’t be using any IDE for these exercises. Also remember not to type in
the line numbers in front of each line; those are just there to make it easier to talk about the code
later.

WorkingWithObjects.java

1 import java.io.File;
2 import java.util.ArrayList;
3 import java.util.Random;
4 import java.util.Scanner;
5
6 public class WorkingWithObjects {
7 public static void main( String[] args ) throws Exception {
8 File f = new File("datafiles/phonetic-alphabet.txt");
9
10 if ( f.exists() == false ) {
11 System.out.println( f.getName() + " not found in this folder. :(");
12 System.exit(1);
13 }
14
Exercise 1: Working With Objects 18

15 ArrayList<String> words = new ArrayList<String>();


16 Scanner alpha = new Scanner(f);
17
18 System.out.print("Reading words from \"" + f.getPath() + "\"... ");
19 while ( alpha.hasNext() ) {
20 String w = alpha.next();
21 words.add(w);
22 }
23 alpha.close();
24 System.out.print("done.\n\t");
25
26 Random rng = new Random();
27 rng.setSeed(12345);
28 // rng.setSeed(23213);
29
30 for ( int n=0; n<3; n++ ) {
31 int i = rng.nextInt( words.size() );
32 String s = words.get(i);
33 System.out.print( s.toLowerCase() + " " );
34 }
35 System.out.println();
36 }
37 }

Once you’ve got the code typed in I’m going to assume that you saved the file WorkingWithOb-
jects.java into a folder called javahard2. If you saved it into a different folder, substitute the
name below.
Open up a terminal window and change into the javahard2 folder:

cd javahard2
ls

(If you’re stuck on a much older version of Windows that doesn’t have Powershell, then you will
have to type dir. Everybody else gets to type ls, though.)
Hopefully you’ll see an output listing that includes:

WorkingWithObjects.java
Exercise 1: Working With Objects 19

That means you’re in the right place. Then you’ll compile the file using the Java compiler, which is
called javac:

javac WorkingWithObjects.java

If this command gives an error about javac itself, then you skipped Exercise 0! Go back and make
sure the JDK is installed and in the PATH, then come back!
Assuming you have good attention to detail and did everything that I told you, this command will
take a second to run, and then the terminal will just display the prompt again without showing
anything else.
However, if you made a mistake, you will see some error. If you have any error messages, fix them,
then save your code, go back to the terminal and compile again.

If you make a change to the code in your text editor, you must save the file before attempting
to re-compile it. If you don’t save the changes, you will still be compiling the old version
of the code that was saved previously, even if the code in your text editor is correct.

Eventually you should get it right and it will compile with no errors and no message of any kind.
Do a directory listing and you should see the bytecode file has appeared in the folder next to your
code:

javac WorkingWithObjects.java
ls

WorkingWithObjects.class
WorkingWithObjects.java

Now that we have successfully created a bytecode file we can run it (or “execute” it) by running it
through the Java Virtual Machine (JVM) program called java:

java WorkingWithObjects
Exercise 1: Working With Objects 20

What You Should See

Reading words from "datafiles/phonetic-alphabet.txt"... done.


juliett uniform foxtrot

Okay, now that that is working, let’s talk about some of the patterns we see in this exercise.
Line 1 imports a “library”. java.io.File contains the definition for a object/class called File. Once
we have imported it, we can create File objects in our code and call methods defined inside those
objects.
The next three lines import three more libraries, each defining an object. Some programming
languages call these imported things “modules” instead of libraries. Same thing.
On line 8 we instantiate a File object and name it f. The File object is passed a String parameter
containing the name of a file to connect itself to.

You should have been provided a folder called datafiles with several files in it, including a text
file named phonetic-alphabet.txt. Make sure this folder is inside the folder where your Java file
is located. Copy or move the folder there if it isn’t already.

On line 9, we now have a File object named f that is somehow connected to the text file on our
computers.
On line 15 we created a second object. This is an ArrayList of Strings named words, and instantiating
it didn’t use any parameters.
On line 16, we create a third object. This one is a Scanner object, and it uses the File object from
before as its parameter.
Finally, on line 26 we instantiate our fourth object: a Random object. Notice the pattern. If you want
to instantiate an object called “Bob”, you’d write code like this:

Bob b = new Bob();

Or maybe:

String s = "Robert";
Bob b = new Bob(s);
Exercise 1: Working With Objects 21

That’s pretty much how Java creates objects. The keyword new is always involved, and the name of
the class (twice) and some parens.
Now let’s look at method calls. A method is a chunk of code inside an object that accomplishes a
single purpose, and “calling” a method means asking the object to execute the code in that method
for you.
On line 10, we call a “method” named exists() that is contained inside the File object f. This
method will return a Boolean value (either true or false) depending on whether or not that file
exists. The code that figures out how to do that is contained inside the library java.io.File that
we imported. Make sense?
Line 11 features another method in the File class: getName(). It returns a String containing the
name of the file associated with the object. If you skip down to line 18 you can also see a method
named getPath() being called.
Line 19 calls the hasNext() method, which is in the Scanner class (our Scanner object is named
alpha. It returns true if there’s text in the file we haven’t read yet.
The next() method reads a single String from the file and then on line 21 we call the add() method
of ArrayLists to add that String to the list.
On line 23 we call the close() method, which closes the Scanner object so that we can’t read from
its file anymore.
Line 27 calls the setSeed() method of the Random class, and line 31 calls the nextInt() method of
the same class. Line 31 also calls the size() method of ArrayLists, and line 32 calls get() to retrieve
a single String out of the list.
Finally line 33 calls a method named toLowerCase(), which is part of the String class. Could you
have figured that out if I hadn’t told you? I hope so, because “toLowerCase()” looks like a method
call, and the variable s is a String.
Okay, so that’s enough for this exercise. The specific details of how this program works aren’t
important, but at this point you should have a good sense of how you do the following in Java:

1. Import libraries containing classes or objects


2. Instantiate (or “create”) an object
3. Call methods on that object

Enough until next time.


Exercise 1: Working With Objects 22

Study Drills
After most of the exercises, I will list some additional tasks you should try after typing up
the code and getting it to compile and run. Some study drills will be fairly simple and some
will be more challenging, but you should always give them a shot.

1. Computers are pretty bad at being “random”. They can only generate a random
sequence of values, but that sequence is typically based on a “seed”. If you use the
same seed, the sequence of random numbers will be the same. (This is useful for
debugging.) Change the seed on line 27 to something else (maybe 23213 or whatever).
Then run the program again and confirm that although the output is different from
before, it doesn’t change when you run the program many times.
Add a comment explaining what seed you picked and what the output was.
Exercise 2: Creating Your Own Single
Objects
In the last chapter, we imported a few objects from Java’s “standard library”: the collection of classes
and methods that are pre-built by the creators of the language.
In this chapter, we will create objects of our own, and each one will contain a single method.
Type up the following code and get it to compile. Save it in your ‘javahard2’ folder with a name of
OldMacDonald.java.

OldMacDonald.java

1 class Cow {
2 public void moo() {
3 System.out.println("Cow says moo.");
4 }
5 }
6
7 class Pig {
8 public void oink() {
9 System.out.println("Pig says oink.");
10 }
11 }
12
13 class Duck {
14 public void quack() {
15 System.out.println("Duck says quack.");
16 }
17 }
18
19 public class OldMacDonald {
20 public static void main( String[] args ) {
21
22 Cow maudine = new Cow();
23 Cow pauline = new Cow();
24 maudine.moo();
25 pauline.moo();
26
27 Pig snowball = new Pig();
Exercise 2: Creating Your Own Single Objects 24

28 snowball.oink();
29 snowball.oink();
30
31 Duck ferdinand = new Duck();
32 ferdinand.quack();
33 }
34 }

What You Should See

java OldMacDonald

Cow says moo.


Cow says moo.
Pig says oink.
Pig says oink.
Duck says quack.

Lines 1-5 define an object called Cow. The definition of the Cow class includes the definition of a
method called moo(). Note that on line 2 it says “public void moo()”, not “public static void moo()”.
Except for main(), you won’t be using the keyword static very much anymore.
Lines 7 through 11 define a class named Pig, containing an oink() method. And lines 13 through
17 define a class named Duck, which contains a quack() method.
Lines 19 to 34 define the class that matches the name of the Java file. Notice that in this file, the class
OldMacDonald has the keyword public in front, but none of the other classes do. In Java, each file
may only have one public class in it, and the name of that public class has to match the name of the
file.
This class contains the main() method in it, which is where the Java Virtual Machine begins when
executing a file. The OldMacDonald class is listed after the other classes in the file, but it would work
the same if the classes were in a different order.
When we run this program, execution begins on the first line of the main() method. Any other code
in the file will only execute if it gets called from inside main().
Lines 22 and 23 instantiate two Cow objects. Lines 24 and 25 call the moo() method on behalf of each
object. This causes execution to jump up to line 3, run the println() statement inside the method,
and return back down below.
Exercise 2: Creating Your Own Single Objects 25

On line 27 we create an instance of a Pig object and then call its oink() method twice. And on line
31 we instantiate a Duck object and call its only method on the next line.
Then on line 33 we hit the close curly brace of the main() method, which typically means the end
of the program.
Do you see? Defining your own objects isn’t so hard, and calling their methods is pretty easy, too,
once you’ve instantiated an object.

Study Drills
1. Try moving the entire definition of the Duck class below the OldMacDonald class.
Does the code still compile and work? Answer in a comment.
2. Inside the main() method, instantiate another object and call its method. (It doesn’t
matter which of the three objects; just pick one.)
Exercise 3: Defining Objects in
Separate Files
In the previous exercise, we defined three objects (actually four if you count the one that had main()
in it), but they were all implemented in the same file. This is not typically how things are done.
Usually Java puts the implementation for each class into its own file, and then there’s another file
that just holds the main() method that instantiates the objects and makes them do their thing. This
class is often called the “driver” class, so usually I’ll put the word “Driver” in the name of the file.
Type up the following code, and put each class into its own file, named as shown. Save them all in
the same folder.

OldMacCow.java

1 public class OldMacCow {


2 public void moo() {
3 System.out.println("Cow still says moo.");
4 }
5 }

After you’ve typed in and saved OldMacCow.java, you should probably try to compile it to make
sure you haven’t made any mistakes before you move on.

OldMacDuck.java

1 public class OldMacDuck {


2 public void quack() {
3 System.out.println("Duck still says quack.");
4 }
5 }

Did you accidentally try to run this file or the first one? Neither one contains a main() method, and
so executing it by itself won’t work.
Exercise 3: Defining Objects in Separate Files 27

OldMacDriver.java

1 public class OldMacDriver {


2 public static void main( String[] args ) {
3 OldMacCow maudine = new OldMacCow();
4 OldMacCow pauline = new OldMacCow();
5 maudine.moo();
6 pauline.moo();
7
8 OldMacDuck ferdinand = new OldMacDuck();
9 ferdinand.quack();
10 }
11 }

Ah, there’s the main() method. Once done you can compile these a few ways.

javac OldMacCow.java
javac OldMacDuck.java
javac OldMacDriver.java

You can compile them one at a time. That works just fine.

javac OldMacCow.java OldMacDuck.java OldMacDriver.java

Although you have probably only used the Java compiler on one file at a time, it will happily compile
as many files as you give it, in order from left to right.
If there’s an error, though, you’ll have to pay attention to the filename in the error message. For
example:

OldMacCow.java:2: error: illegal start of type

This error message is on line 2 in the file OldMacCow.java, whereas the next mistake is on line 6 or
earlier in the file OldMacDuck.java for this error message:

OldMacDuck.java:6: error: reached end of file while parsing


Exercise 3: Defining Objects in Separate Files 28

So just watch for that.

javac OldMac*.java

If the filenames you’re trying to compile are similar, you can compile them all at once with something
like this. The star/asterisk gets expanded by your terminal into all filenames in the current folder
that begin with OldMac and which end in .java. (This includes the file OldMacDonald.java from the
previous exercise. Which is fine, compiling doesn’t “combine” the files in any way, it just converts
each file one at a time into its own bytecode (.class) file.)

javac OldMacDriver.java

So, what magic is going on here? Only one file name? Well, what happens is that javac starts
compiling OldMacDriver.java. On line 3 we refer to an object called OldMacCow. There’s no object
called that defined in this file. And there are no import statements to import a class called that, either.
So the Java compiler goes hunting. It knows it needs an object called OldMacCow, which would be
implemented in a bytecode file named OldMacCow.class. If this file exists in the current folder, then it
pulls the definitions from this bytecode file automatically! (This is a big deal for C++ programmers.)
And if there’s no bytecode file in the current folder, it then looks for a source code file called
OldMacCow.java that it can compile to create that bytecode file. If such a file is in the current folder,
it’ll just automatically compile it for you.
It does this for any objects referenced in the file you’re compiling. If it can resolve all the
dependencies itself, it’ll do so. If not, it’ll throw a compiler error about the undefined symbol it
couldn’t find.
So, to sum up, from here until the end of the book you should probably compile each file as you
finish it to make sure there aren’t any mistakes. But if you’re lazy or just confident, it is usually
okay to just compile the one file containing the main(), and let the compiler find the rest of the files
for you.

What You Should See


As you might suspect, when executing the bytecode, you only need to run the file containing the
main() method.

java OldMacDriver
Exercise 3: Defining Objects in Separate Files 29

Cow still says moo.


Cow still says moo.
Duck still says quack.

You’ll notice that the process of actually instantiating the objects or calling their methods isn’t any
different. (See lines 3 through 9 in the driver file.) You just make an instance of an object, then call
its method, just like before.
Hopefully this process of doing one program that is broken up into multiple files makes sense.
Because that’s what we will be doing from here on out in the rest of the book!
(I’m not trying to be difficult; that’s just how object-oriented programming works. Code is broken
up into classes/objects each in their own file and those objects are combined to make a working
program. I’ll talk more about the reasons behind this in the chapters to come.)

Study Drills
1. Edit the message in the moo() method inside OldMacCow. Save the file with the
changes but do not compile it! Then edit the message in the quack() method inside
OldMacDuck(). Save the file but don’t compile it either. Then confirm that the
single command javac OldMacDriver.java will compile all three files. Answer in
a comment in the driver file how things worked out.
Exercise 4: Fields in an Object
So far we have only looked at methods inside of objects. But most objects have variables inside them,
too, called “fields” (or sometimes “instance variables”).
This program will illustrate accessing fields in an object.
Type up this code and save it in its own file, named as indicated.

TVActor.java
1 public class TVActor {
2 String name;
3 String role;
4 }

Then type up this one and save it in the same folder as the first file.

TVActorDriver.java
1 public class TVActorDriver {
2 public static void main( String[] args ) {
3 TVActor a = new TVActor();
4 a.name = "Thomas Middleditch";
5 a.role = "Richard Hendricks";
6
7 TVActor b = new TVActor();
8 b.name = "Martin Starr";
9 b.role = "Bertram Gilfoyle";
10
11 TVActor c = new TVActor();
12 c.name = "Kumail Nanjiani";
13 c.role = "Dinesh Chugtai";
14
15 System.out.println( a.name + " played " + a.role );
16 System.out.println( b.name + " played " + b.role );
17 System.out.println( c.name + " played " + c.role );
18 }
19 }

Remember that you only need to compile the one file containing the main() method, though it is a
good idea to test compiling each file as you finish it to make sure it’s correct before moving on.
Exercise 4: Fields in an Object 31

What You Should See

javac TVActorDriver.java
java TVActorDriver

Thomas Middleditch played Richard Hendricks


Martin Starr played Bertram Gilfoyle
Kumail Nanjiani played Dinesh Chugtai

So the class TVActor contains two instance variables, and they are both Strings. The first variable is
called name and the second is called role.
They are called “instance” variables because each instance (copy) of the object gets its own copies
of the variables.
That is, just after line 11 is over, there are three instances of the TVActor class created. public class
TVActor makes a pattern or recipe or blueprint of sorts, and then line 3 actually sews together the
clothing or cooks the recipe or builds the structure when it instantiates the object.
And so the instance named a has a copy of the name variable and a copy of the role variable. We
can put values into a’s copies of these variables as shown on lines 4 and 5, though we’ll see later in
the book that this is considered bad style.
Line 7 creates a second instance of the class, with its own copies of the instance variables.
And line 11 creates a third instance of the class, which also has its own copies of the variables. So
by line 14, there are at least nine objects floating around in memory: three TVActor objects and six
String objects (two per TVActor).

Study Drills
1. Add a third instance variable to the TVActor class, either a String, an int, or a double.
Name it something suitable, then add code to the driver class to put values for each
instance of the TVActor object.
Also add code to print out the new field.
Exercise 5: Programming Paradigms
Before I get too far into the weeds of object-oriented programming (OOP), it might be useful to
see the difference between OOP-style code and doing the same program in other programming
paradigms.
I created a short program that does four things:

1. Allow the human to enter a message.


2. Reverse the order of the characters in the message.
3. “Camel-case” each word. That is, convert “Hello how are you” to “HelloHowAreYou”.
4. Display the result.

First, here’s the program using as much of a simple, monolithic style as Java will allow. You don’t
have to type this program in unless you really want to.

StringFunMonolith.java

1 import java.util.Scanner;
2
3 public class StringFunMonolith {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 // input it
8 System.out.print("Enter a message: ");
9 String msg = keyboard.nextLine();
10
11 // reverse it
12 String rev = "";
13 for ( int i=msg.length()-1; i>=0; i-- )
14 rev += msg.substring(i,i+1);
15
16 // camel-case it
17 String lower = rev.toLowerCase();
18 String[] words = lower.split(" ");
19 String result = "";
20 for ( String w : words )
21 result += w.substring(0,1).toUpperCase() + w.substring(1);
Exercise 5: Programming Paradigms 33

22
23 // display it
24 System.out.println(result);
25 }
26 }

What You Should See

Enter a message: ^C

So, lines 8-9 input the message, lines 12-14 reverse it, lines 17-21 camel-case it, and line 24 displays
it. Don’t worry too much if you don’t understand the details of the camel-case part.
Next, I have coded the same program in a “functional” style. Functional style uses only functions
with a few inputs and only one output each. The functions don’t share information with each other
except through their inputs and outputs.
Again, there’s no sense typing up this version unless you want the practice. (It does work, though.)

StringFunFunctional.java

1 import java.util.Scanner;
2
3 public class StringFunFunctional {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 // input it
8 System.out.print("Enter a message: ");
9 String msg = keyboard.nextLine();
10
11 // reverse it
12 msg = reverse(msg);
13
14 // camel-case it
15 msg = camelCase(msg);
16
17 // display it
18 System.out.println(msg);
19 }
20
Exercise 5: Programming Paradigms 34

21 public static String reverse( String s ) {


22 String rev = "";
23 for ( int i=s.length()-1; i>=0; i-- )
24 rev += s.substring(i,i+1);
25
26 return rev;
27 }
28
29 public static String camelCase( String s ) {
30 String[] words = s.toLowerCase().split(" ");
31 String result = "";
32 for ( String w : words )
33 result += w.substring(0,1).toUpperCase() + w.substring(1);
34
35 return result;
36 }
37 }

Lines 1-9 are the same as the previous version, because it’s kind of hard to get input from the human
in Java any other way.
But you can see on line 12, the message (in the variable msg) is passed in to a function called reverse,
and the result is put back into msg, overwriting the previous value. This is a bit more understandable.
And lines 21-27 are the reverse() function itself. It’s the same code as lines 12-14 of the previous
assignment, but there’s a little extra setup to name the function and name the parameter and also an
extra line to “return” the final result. Notice, though, that we get to call the input s instead of having
to care that it’s really called msg elsewhere. It’s a bit nice to be able to call that variable whatever
we want without caring what happens in other parts of the program.
Line 15 is the camelCase function call, and lines 29 through 36 are the function definition. Notice
that on line 29 we were free to call the parameter s without caring about other parts of the program.
Is the variable in main() really called s?
Doesn’t matter.
Is some other function already using a variable called s?
Doesn’t matter.
What variable is the return value going into?
It doesn’t matter. We can call it result or rev or whatever suits us.
Another nice thing about a functional style of programming is that since each function receives an
input and returns an output, functions can be chained very compactly.
Here is the same functional version, but with the functions all nested inside each other.
Exercise 5: Programming Paradigms 35

StringFunFunctionalShort.java

1 import java.util.Scanner;
2
3 public class StringFunFunctionalShort {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 System.out.print("Enter a message: ");
8 System.out.println(camelCase(reverse(keyboard.nextLine())));
9 }
10
11 public static String reverse( String s ) {
12 String rev = "";
13 for ( int i=s.length()-1; i>=0; i-- )
14 rev += s.substring(i,i+1);
15
16 return rev;
17 }
18
19 public static String camelCase( String s ) {
20 String[] words = s.toLowerCase().split(" ");
21 String result = "";
22 for ( String w : words )
23 result += w.substring(0,1).toUpperCase() + w.substring(1);
24
25 return result;
26 }
27 }

You read line 8 from the inside out. The inner-most thing happens first: keyboard.nextLine()
is called. Once it’s done, it returns a String, which we pass immediately to reverse(), then
camelCase(), then println().

Some programs are more difficult in a functional style, but when it works it’s really nice and clean-
looking.

By the way, formulas in a spreadsheet program like Microsoft’s Excel, Apple’s Numbers
or LibreOffice’s Calc are programmed in a functional style. This is a tricky way to code,
as you know if you’ve ever struggled to get one right!
Graphics-processing shaders (like in OpenGL or Direct3D) are usually written in a
functional style, too, and that makes them well-suited for parallel processing.
Exercise 5: Programming Paradigms 36

Okay, finally let’s do this same little program in an object-oriented style. We’ll use two files as usual:
one containing our class/object, and one with the driver. These are the ones you should type in.

StringFunObject.java
1 public class StringFunObject {
2
3 String message;
4
5 public void setMessage( String s ) {
6 message = s;
7 }
8
9 public String getMessage() {
10 return message;
11 }
12
13 public void reverse() {
14 String rev = "";
15 for ( int i=message.length()-1; i>=0; i-- )
16 rev += message.substring(i,i+1);
17
18 message = rev;
19 }
20
21 public void camelCase() {
22 String[] words = message.toLowerCase().split(" ");
23 String result = "";
24 for ( String w : words )
25 result += w.substring(0,1).toUpperCase() + w.substring(1);
26
27 message = result;
28 }
29 }

There’s something new in this one. On line 3 there’s an instance variable / field, just like you learned
about in the previous exercise.
Notice that on line 6, there’s a method that stores a copy of the parameter s into a variable named
message. Where is this message declared? It’s the field. We’ll look more at this in later chapters, so
don’t worry too much about it for now.
Just remember for this code, any time that “message” is referenced, it’s the instance variable. All
the other variables are “local”, which means they only exist inside the method in which they are
defined.
Exercise 5: Programming Paradigms 37

So, here’s the code for the driver. Type this one in, too.

StringFunOODriver.java
1 import java.util.Scanner;
2
3 public class StringFunOODriver {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 // input it
8 System.out.print("Enter a message: ");
9 String msg = keyboard.nextLine();
10
11 StringFunObject sfo = new StringFunObject();
12 sfo.setMessage(msg);
13 sfo.reverse();
14 sfo.camelCase();
15
16 // display it
17 System.out.println( sfo.getMessage() );
18 }
19 }

What You Should See (Reminder)

Enter a message: ^C

(There’s the output again so you don’t have to scroll up for it.)
This is very typical object-oriented code. Line 11 declares and instantiates an object. Line 12 calls the
setMessage() method of that object, and passes the message into it as a parameter. Then the next
few changes happen inside the object: the message gets reversed, then the message gets camel-cased.
Finally on line 17 of the driver we call the getMessage() method of the object, and it returns to us
the modified String for printing.
Maybe you don’t like the object-oriented style. Maybe you think the monolithic version is better, or
maybe the functional version.
You know what? I agree with you. Object-oriented programming isn’t a very good fit for a tiny
program like this. OOP works best when the programs are large and complicated (like 10,000 lines
of code or more).
Exercise 5: Programming Paradigms 38

Whenever I write a program to help me automate something annoying, I almost never code it in an
object-oriented style if it’s going to be only 500 lines of code or less.
I write it in a monolithic style if it’s just going to be 10-50 lines long. I use functions when it’s 50-500
lines long, and I start out object-oriented if it’s going to be much bigger than that.
Unfortunately the rest of this book is going to be a little weird. I’m going to use the object-oriented
style even for tiny 20-line programs. It’ll be gross. You might not like it. You might think “This
program would be so much simpler if he would just….”
But I can’t teach you object-oriented programming using only nice huge 1,000 line perfect examples
where OOP makes sense. (Well, I could, but this book would be about 800 pages longer and I wouldn’t
have finished writing it yet!) Instead I have to teach you OOP using small silly example programs
where the OOP feels weird and forced but the programs are small enough to understand.
Once you’re done with this book, you’re free to code for the rest of your life in a non-object-oriented
way. But, if someone dumps a 20,000 (or two-million!) line program on you that uses OOP just to
have any hope of preventing bugs, then you’ll have the tools to make sense of it.
Deal?

Study Drills
1. Using the reverse() method as a guide, add a method to the object-oriented version
to remove half of the letters from the message. (It can be the first half, the last half,
every other letter or whatever scheme you like.) Then add a call for that method to
the driver.
Exercise 6: Accessing Fields in
Methods
In this exercise, we are going to look in closer detail at the concept of an object having fields
and methods that access those variables. This was introduced in the OOP-version of the previous
exercise.
Here is the source code for the object, which will take a phrase and a number and produce a String
with the specified number of copies of that message.

PhraseRepeater.java

1 public class PhraseRepeater {


2
3 String phrase;
4 int repeats;
5
6 public void setValues( String p, int r ) {
7 phrase = p;
8 repeats = r;
9 }
10
11 public String getRepeatedPhrase() {
12 String result = "";
13 for ( int i=0; i<repeats; i++ )
14 result += phrase;
15 return result;
16 }
17 }

This class has two fields / instance variables, a String named phrase and an int named repeats.
Remember that if we were to instantiate several versions of this object in a driver, each instance of
the object would have its own copies of both fields.

“Instance variables” are variables defined in a class but outside of any method. A “field”
is just a generic name for a member of a class. They mean pretty much the same thing,
so I will use them interchangably in this book.
Random documents with unrelated
content Scribd suggests to you:
It was quite a treat now to Todd, and put him in mind of old times,
to arrange his apparatus for giving this wretched man a tumble into
the vaults below. He went into the parlour and drew the bolt, when
away went the man and the chair, and the other chair that was on
the reverse side of the plank took the place of that which had gone.
"Ha! ha!" shouted Todd. "This is grand—this is most glorious! Ha!
ha! Who would have thought, now, that I should ever live to be at
my old work again in this house? It is capital! If that fall has not
broken his neck, it's a wonder. It used to kill five out of seven; that
was about the average—ha!"
Todd didn't fasten the bolt again, but went at once for the other
man. He was sitting up!
Todd staggered back for a moment, when he saw him in that
position looking at him. The man rubbed his eyes with his hands and
said in a weak voice—
"Good God! what is it all about?"
Todd placed the light on the floor within the parlour, so that it shed
sufficient rays into the shop to let him see every object in it; and
then, with a cry like that of some wild beast rushing upon his prey,
he dashed at the man.
The struggle that ensued was a frightful one. Despair, and a feeling
that he was fighting for his life, nerved the man, who had recovered
just in time to engage in such a contest, and they both fought their
way into the shop together. Todd made the greatest exertions to
overcome the man, but it was not until he got him by the throat,
and held him with a clutch of iron, that he could do so. Then he
flung him upon the chair, but the man, with a last effort, dragged
Todd after him, and down they both went together to the vault
below!
Todd And The Bow Street Officers—The Death Grapple.
CHAPTER CXLVII.
SIR RICHARD BLUNT AND CROTCHET COMMENCE
THEIR SEARCH FOR TODD.

When Sir Richard Blunt left Chelsea, he felt that he had given a
sufficient warning to all who could feel in any way personally
interested in the escape of Sweeney Todd from the punishment that
his numerous crimes merited.
He rode direct to the office of the Under Secretary of State for the
Home Department, and his name at once procured him an interview.
This was not the supercilious personage who once before, upon an
occasion of Sir Richard Blunt calling upon him regarding Sweeney
Todd, had exhibited so much indifference upon the subject, and Sir
Richard was received as he ought to be.
"I have waited upon you, sir," said the magistrate, "to say that I
have now made every arrangement that is possible for the purpose
of counteracting any mischief that the man, Todd, might strive to do;
and I think it very likely that I may not have the pleasure of seeing
or communicating with you for some time."
"Then you still think, Sir Richard, of going personally after the
notorious ruffian?"
"I do, sir. I feel that in some sort I am bound to rid society of that
man. I had so large a share in his former apprehension, and in his
conviction, that I feel his escape quite a personal matter; and I have
no hesitation in saying that I shall not feel at ease until I have again
placed him in the hands of the law."
"It is most desirable that he should be so placed, Sir Richard, and I
have only two things to say to you upon the subject. One is, that I
hope you will be careful of your own safety in the affair; and the
other is, that anything we can do or any facilities we can throw in
your way, you may most unhesitatingly command in the prosecution
of your most praiseworthy enterprise."
"I thank you, sir. I shall take one man with me. His name is
Crotchet; and I should wish that in your name I might tell him that,
in the event of our search for Todd being successful, he may count
upon an adequate reward."
"Certainly! He shall have the whole reward, Sir Richard; and as for
yourself, the ministry will not be unmindful of your service in a way
that I am sure will be more gratifying to you than an offer of
money."
"Sir, I thank you. The government has already, upon more than two
or three occasions, been sufficiently liberal to me as regards money
to place me in a good position, and I have now no further desires of
that sort. I will bid you good morning, sir, and at once start upon the
expedition in search of Sweeney Todd. If he be alive and above
ground in this country, I will have him."
"If anybody will, you will, Sir Richard."
The magistrate left the place, and repaired at once to his private
office, which was close at hand, in Craven Street. There our old
friend, Crotchet, was waiting for him.
"Well, Crotchet," said Sir Richard, "I have just seen the Secretary of
State, and if we catch Todd, you are to have all the money."
"All on it, sir? Oh, my eye! No, I doesn't want all on it, Sir Richard. I
isn't a pig."
"I never thought you were, Crotchet; but you may make up your
mind to the whole of the reward, as the government will provide for
me in another way; so you know now, at starting, what you have to
expect, and it will keep you in good heart during all the botheration
we may have in looking after this man."
"Why, so it will, sir, you see, so it will, and if I do catch him and get
all this tin as is offered as a reward for him, I shall retire from the
grabbing business, you see, sir."
"What will you do then, Crotchet?"
"Set up a public-house, sir, and call it 'The Crotchet's Arms,' to be
sure. That's the sort of ticket for me."
"Well, Crotchet, you will be quite at liberty to do what you like; and
now let us at once start on our errand. We will, from the door of
Newgate, see if we cannot trace the progress of this man, with his
new friend, that rascal, Lupin."
A tap sounded on the panel of the door of the room in which
Crotchet and Sir Richard were conversing.
"Come in," said the magistrate, and his clerk entered with a written
paper in his hand.
"Here, sir," he said, "is a report from a city officer, which will give a
clue to the route that Todd and Lupin have taken, sir."
"Ah, that is welcome. Let me see it. 'Two men broke into the house
of Alderman Stanhope; one a tall man with a large face—the other,
shorter.' Humph! Not a doubt of it. I will go and see about it. No
doubt it was Todd and his new friend Lupin. This is something of a
clue, at all events however slight, and may, after all, put us upon the
right track. Come on, Crotchet, we will do the best we can in this
matter. Have you your pistols in good order?"
"Yes, yer honour, and a pair of darbies in my pocket, that if once
they get on the wrists of old Todd, he will find it no such easy matter
to get them off again."
"That is right. I only want to get face to face with the ruffian, and
then I will engage that he shall not be much further trouble to
society or to individuals."
Sir Richard Blunt and Crotchet proceeded then at once to the house
in the City, into which Lupin and Todd, it will be recollected, had
made a violent entry, and from which they had been so gallantly
repulsed by the young lady. Then, from the description of the
assailants, not a shadow of a doubt remained upon the magistrate's
mind that they were the parties he sought; but there all clue seemed
to be lost.
He and Crotchet stood in the street looking about them rather
despairingly; and then they thought of going to the round-house
close to Finsbury; and when they got there, they found an officer,
who reported that two men answering the description of the
fugitives had been seen making their way westward; and he had
met a woman who had passed them, and who had heard the words
"money," and "Caen Wood."
This was, in good truth, most important intelligence, if it could be
relied upon; and that was the only kind of doubt that Sir Richard
had. He spoke to Crotchet about it.
"What do you think, Crotchet? Is it worth while to follow this
seeming clue to Highgate?"
"Yes, yer honour, it is. We can go there and back again while we are
considering about it here. It's clear enough as we shan't get any
other news in this part of the town; and so I advises that we go off
at once to Highgate, and calls at every public-house on the road."
"Every public-house?"
"Yes, yer honour. Todd won't do without his drops of something
strong to keep him a-going. These kind of feelings go down—down,
till they haven't the heart to say don't, when the hangman puts the
noose round their necks, if they haven't their drops. It's brandy, yer
worship, as keeps 'em a going."
"I do believe, Crotchet, that there is a great deal of truth in what
you say; and that it is only by use of stimulants that they keep up a
kind of artificial strength, as well as drowning reflection; and so they
go blundering on in the career of crime."
"You may depend upon it, sir. They'd cut their own throats in a
week, If it wasn't for the tipple, yer honour."
Acting then upon the practical advice of Crotchet, which in a great
measure accorded with his own convictions, Sir Richard Blunt
repaired to a livery-stable, and hired two good horses. He found no
difficulty in getting them, upon declaring who he was; and so, well
mounted, he and Crotchet went upon the very road that had been
so recently traversed by the two culprits, Todd and Lupin.
At the first public-house they came to they got no news; but at the
second they were told, that two men, answering the description they
gave of those they sought, had called and had some brandy.
The magistrate no longer doubted but that he was upon the right
track now. With such a feeling, he pushed on, making what inquiries
he could on the road; but until Highgate was reached they got no
further news, and then, by dint of diligent ferreting out, they found a
woman who had seen two men go down Swains Lane, and from the
description she gave of them, there could be no doubt but that they
were Todd and Lupin. Now as Swains Lane led direct to Caen Wood,
it was a great confirmation of the former intelligence; and Sir
Richard made up his mind to search the wood, as well as it could be
done by him and Crotchet.
They engaged a lad from Highgate to come with them, and to take
care of the horses, while they should go into the wood; but they did
not say one word to him regarding their object in going there, nor
could he possibly suspect it. Sir Richard and Crotchet both thought it
would be much more prudent to keep that to themselves, than to
put it in the power of a boy to gossip about it to every one who
might chance to pass that way, while he was minding the horses.
When the wood was reached, Sir Richard said to the lad—
"Now, my boy, we shall not be very long gone, but you will bear in
mind that if we are absent longer than you expected, you will be
paid in proportion; so don't be impatient, but walk the horses up and
down this bit of the lane; and think that you have got a very good
job."
"Thank you, sir," said the boy. "Across that there meadow is the
nearest way to the wood. I seed two fellows go that way, early this
morning, and one on 'em was the ugliest fellow I ever saw, and he
calls out to the other—'Come along Lupin, we shall be all right in the
wood now. Come along, Lupin—Ha! ha!'"
"You heard that?"
"Yes, sir, I did. You see, I was sloe-gathering in the hedge, and they
don't let you do it, cos they say you breaks down all the young
twigs, and spoils the hedge, and so you does; and so, sir, when I
heard footsteps a-coming, I hid myself right down among the long
grass, so that they did not see me."
Mr. Crotchet gave a long whistle.
"Very good," said Sir Richard; "we shall be back with you soon. You
take good care of the horses."
"I will, sir."
"What do you think of that, Crotchet?" said Sir Richard, as they
made their way into the very meadow across which Todd and Lupin
had run to get to Caen Wood.
"It's the finger o' Providence, yer worship."
"Well, I cannot deny, Crotchet, but that it may be so. At all events,
whether it be Providence or chance, one thing is quite certain, and
that is, that we are on the track of those whom we seek."
"Not a doubt o' that, sir. Into the wood here they have been, but
whether they have staid here or not, you see, sir, is quite another
affair. But it's worth looking well to; at all events yer worship, and I
shan't leave an old tree in this here place as we is coming to, that I
shan't walk right round and have a jolly good look at, somehow or
another."
"Nor I, Crotchet. They may know of some hiding-place in this wood,
for all we know to the contrary, and if they do, it strikes me we shall
ferret them out."
"In course we shall, sir; and here we is."
They had reached the wood by this time, and before plunging into
its recesses the magistrate looked carefully about him, and Crotchet
did the same.
"Do you think, your worship, there's a chance of such a fellow as
Todd staying long here?"
"Why do you think that?" said Sir Richard.
"Why, sir," said Crotchet, putting his head on one side, "this here is a
sort of place that makes a man think; and always when I am in a
quiet place like this, with the beautiful trees all about me, and the
little birds a singing, and the frogs a croaking, it makes me think of
things that I don't always think of, and of those as has passed away
like spirits, and as we may meet in t'other world nor this, sir."
"Indeed, Crotchet, I do not wonder that the silence and solitude of
nature should have that effect upon you."
"Exactly, sir. In course, it ain't for me to say whether in this ere
world there ought to be prigs, and sneaks, and cracksmen, and all
that sort of thing or not; but I will say, sir, as I'm not a little
surprised how anybody can do anything very wrong, sir, in the
country."
"Indeed, Crotchet?"
"Yes, sir; it has an effect on me. When I gets among the old trees
and sees the branches a waving about, and hear the wind a
moaning among 'em, it makes me think as there ain't a great deal in
this world as is worth the bothering about, you see, sir; and least of
all is it worthwhile doing anything that ain't the right thing."
"You are quite a philosopher, Crotchet, although you are not the first
nor the only one upon whom the beauties of nature have produced
an elevating effect. The reason I fear is that you are not familiar
with such places as these. You are town-bred, Crotchet, and you
pass your life among the streets of London; so such places as this
affect you with all the charm of novelty, while those who are born in
the country know nothing and care nothing for its sights and
sounds."
"That's about it, sir, I shouldn't wonder," said Crotchet; "but I feels
what I feels and thinks what I thinks."
They now had fairly penetrated into Caen Wood; and we may here
appropriately remark, that Caen Wood was much more of a real
wood then, than it is now, when it is rather an imitation of one than
one in reality. The smoke and the vegetation-killing vapours of
London have almost succeeded in begriming the green trees even at
that distance off; and in a few short years Caen Wood, we fear, will
be but a thing of tradition in the land.
So time works his changes!
Sir Richard Blunt, with long practised sagacity, began his hunt
through the wood. It could scarcely be said that he expected to find
Todd there, but he would be satisfied if he found some conclusive
evidence that he had been there, for that would show him that he
was upon the track of the villain, and that he was not travelling wide
from the course that Todd had taken. The idea that he might have at
once, on foot, made his way to some part of the coast, haunted Sir
Richard, notwithstanding all the seemingly conclusive evidence he
had to the contrary; and knowing well, as he did, how very little
reliance ought to be placed upon personal descriptions, he did buoy
himself up with many hopes consequent upon the presumed identity
of Todd with the person who had been seen by those who had
described him.
Taking a small piece of chalk from his pocket, the magistrate marked
a few of the trees in the different directions where they searched, so
that they might not, amid the labyrinths of the wood, give
themselves increased trouble; and in the course of half an hour they
had gone over a considerable portion of the wood.
They paused at an open spot, and Crotchet lifted from the ground a
thick stick that appeared to have been recently cut from a tree.
"This is late work," he said.
"Yes; and here are the marks of numerous footsteps. What is the
meaning of this strange appearance on the ground, as if something
had been dragged along it?"
Crotchet looked at the appearance that Sir Richard pointed out, and
then with a nod, he said—
"Let's follow this, Sir Richard. It strikes me that it leads to
something."
CHAPTER CXLVIII.
SHOWS HOW TODD HAD A VERY NARROW ESCAPE
INDEED.

There was something in the tone of Crotchet that made the


magistrate confident he suspected something very peculiar, and he
followed him without a word.
The track or trail upon the ground was very peculiar, it was broad
and defined, and had turned in the direction that it went every little
weed or blade of grass that was within its boundaries. A number of
decayed leaves from the forest trees had likewise been swept along
it; and the more any one might look at it the more they must feel
convinced that something heavy had been dragged along it.
What that something heavy was, Mr. Crotchet had his suspicions,
and they were right.
"This way, your worship," he said, "this way; it goes right into this
hedge as nicely as possible, though the branches of these bushes
are placed all smooth again."
As he spoke, Crotchet began to beat the obstructing branches of a
wild nut tree and a blackberry-bush, that seemed, by their entwining
arms, to have struck up a very close sort of acquaintance with each
other; and then he suddenly cried out—
"Here it is, sir."
"What, Crotchet?"
"The dead 'un."
"Dead! You don't mean to say that one such is here, and that the
dead body of Todd is in the thicket?"
"Come on, sir, I don't think it is him. It don't seem long enough; but
here's somebody, as safe as possible, sir, for all that. Push your way
through sir: it's only prickles."
The magistrate did push his way through, despite the vigorous
opposition of the blackberry-bush; and then—lying upon its face—he
saw the dead body of a man.
The readers of this narrative could have told Sir Richard Blunt what
that body had been named while the breath of life was in it; but
neither he nor Crotchet could at first make up their minds upon the
subject.
"Do you know him?" said Sir Richard.
"I guess only."
"Yes, and you guess as I do. This is Lupin, Todd's prison companion,
and the companion in his escape."
Crotchet nodded.
"I went to Newgate," he said, "and had a good look at him, so that I
should know him, sir, dead or alive; so I'll just turn him over, and
have a good look at his face."
With this, Crotchet carefully—by the aid of his foot—turned over the
body, and the first glance he got at the dead face satisfied him.
"Yes, your worship," he said, "Lupin it is, and Todd has killed him.
You may take your oath of that."
"Not a doubt of it: such is the result of the association of such men.
Todd has found him, or fancied he should find him, an encumbrance
in the way of his own escape, and has sought this wood to take his
life."
"That's about it, sir."
"And now, Crotchet, we may make certain of one thing, and that is,
that Todd is not in this wood, nor in this neighbourhood either. I
should say, that after this deed, the first thing he would do would be
to fly from this spot."
"Not a doubt of that, your worship; but the deuce of it is to find out
which way he has gone."
"We must be guided in that by the same mode of inquiry, Crotchet,
that brought us here. We were successful in tracing him to this
wood, and we may be equally successful in tracing him from it. We
must go into the village of Hampstead, and give information about
this dead body; and we will make there what inquiries we can."
They were neither of them very anxious to remain in Caen Wood,
after discovering how it was tenanted; and in a very short time they
were mounted again, and went along the lane until they emerged
upon Hampstead Heath, and so took the road to the village, where
Sir Richard gave information to the authorities concerning the finding
of the body of Lupin.
There, too, he heard that a man answering the description of Todd
had passed through the village, and refused to partake some
questionable brandy, at a public-house, on its outskirts. This man
was evidently proceeding to London. Crotchet heard this information
with great attention; and when he and Sir Richard Blunt were alone,
he said—
"I tell you what it is, sir—the country will never suit Todd."
"How do you mean, Crotchet?"
"I mean, sir, that, in my opinion, he has gone back to London again.
The country, sir, ain't the sort of place for such men as he is. You
may depend upon it, he only came to the little wood to get rid of
Lupin, and he has gone back to try and hide in London till the row is
over."
"You really think so?"
"I do, sir; and if we want to find him, we must go, too."
"Well, Crotchet, of one thing I am pretty well convinced, and that is,
that he is not in this part of the country, for after the murder in the
wood, which he will be in continual fear of being discovered, it is not
likely he would stay about here; and so, as we have traced him a
little on the road to London, we may as well, for all we know to the
contrary, assume that he has gone there at once."
"Come on, then, sir," said Crotchet; "I feel's what you call's a sort of
a—Oh, dear me, what is it? A presentment—"
"A presentiment, Crotchet."
"Ah, sir, that's it. I feel that sort of thing that old Todd will try and
hide himself in some old crib in London, and not at all trust to the
country, where everybody is looked at for all the world as though he
were a strange cat. Lord bless you, sir, if I had done anything and
wanted to hide, I should go into the very thick of the people of
London, and I ain't quite sure but I'd take a lodging in Bow Street."
Sir Richard Blunt was himself very much of Crotchet's opinion
regarding Todd's proceedings, for his experience of the movements
of malefactors had taught him that they generally, after their first
attempt to try to get away, hover about the spot of their crimes; and
it is a strange thing, that with regard to persons who have
committed great crimes, there is a great similarity of action, as
though the species of mind that could induce the commission of
murder from example, were the same in other respects in all
murderers.
To London, then, with what expedition they could make, Sir Richard
Blunt and Crotchet went, and although they made what inquiry they
could, they found no news of Todd. And now we must leave them
for awhile, thrown completely out in all their researches for the
escaped criminal, while we once more proceed to the house in Fleet
Street, where we left Todd in rather an uncomfortable situation.
It will be recollected that, locked in the grasp of the officer, Todd and
that individual had gone down with the chair through the opening in
the floor of his shop.
This was the first time that Todd had undertaken that mode of
getting into the cellars of his house; and when he found the chair
going, he gave himself up for lost, and uttered a cry of horror. It
seemed to him at that moment as if that were the species of
retribution which was to come over him—death by the same
dreadful means that had enabled him so often to inflict it upon
others.
No doubt Todd's anticipations of being dashed to destruction upon
the stones below would have been correct had he gone down alone,
or had there been no one already immediately beneath the trap-door
in the shop flooring; but as it was, he fell, fortunately for him,
uppermost, and they both, he and the officer, fell upon the other
man who had gone down only a short time previous. That saved
Todd; but he was terribly shaken, and so was the officer, and it was
a few moments before either of them recovered sufficiently to move
a limb.
The lives of those two depended upon who should recover his
strength and energies first. Todd was that man. Hate is so much
stronger a passion than every other, and it was under the influence
of that feeling that Todd was the first of the two to recover; and the
moment he did so, the yell of rage that he uttered really might have
been heard in Fleet Street. It was very indiscreet of Todd, but at that
moment he thought of nothing but revenge. His own safety became
a secondary consideration with him.
He grasped the officer by the throat!
At the moment that, by the feel only, for that place was in the most
profound darkness, Todd felt sure that he had the officer by the
throat, he knew that his triumph was certain. It would have been as
vain a thing to attempt to escape the chances of destiny, as to
dream of avoiding the grasp of that iron hand that now closed upon
the throat of the unfortunate officer.
It was just then, though, that the officer began to recover a little
from the shock of his fall. It was only to recover to die. Better for
him would it have been had he slept on in insensibility to the pangs
that were awaiting him; but that was not to be.
"Ah, wretch!" shrieked Todd, "so you thought you had me? Down—
down to death!—Ha!—ha!"
The officer struggled much, and dashed about his feet and arms, but
all was in vain.
"Ha!—ha!" laughed Todd, and that hideous laugh awakened as
hideous an echo in the dismal place. "Ha!—ha! I have you now. Oh!
but I should like to protract your death and see you die by inches!
Only that my time is precious, and for my own sake, I will put you
quickly beyond the pale of life."
The man tried to cry out; but the compression upon his throat of
those bony fingers prevented him. He had his hand at liberty, and he
caught Todd by the head and face, and began to do him as much
mischief as he could. There was for a few seconds a fierce struggle,
and then Todd, keeping still his right hand clasped about the throat
of his victim, with the left laid hold of as much of his hair on the
front of his head us he could, and raising his head then about six
inches from the stone floor on which it had rested, he dashed it
down again with all his might.
The officer's arms fell nerveless to his sides, and he uttered a deep
groan.
Again Todd raised the head, and dashed it down, and that time he
heard a crashing sound, and he felt satisfied that he had killed the
man.
There was now no further use in holding the throat of the dead man,
and Todd let him go.
"Ha!—ha!" he said. "That is done. That is done—Ha! Now am I once
more lord and master in my own house—once again I reign here
supreme, and can do what it may please me to do. Ha! this is
glorious! Why, it is like old times coming back to me again. I feel as
if I could open my shop in the morning, and again polish off the
neighbourhood. It seems as if all that had happened since last I
stropped a razor above, had been but a dream. The arrest—the trial
—the escape—Newgate—the wood at Hampstead! All a dream—a
dream!"
He was silent, and the excitement of the moment of triumph had
passed away.
"No—no," he said. "No! It is too real—much too real! Oh, it is real,
indeed. I am the fugitive! The haunted man without a home—
without a friend; and I have this night nor any other night any place
in which I may lay my head in safety. I am as one persecuted by all
the world, without hope—without pity! What will now become of
me?"
A low groan came upon Todd's ear.
He started, and looked around him. He tried hard to pierce with his
half-shut eyes the intense darkness, but he could not; and muttering
to himself—"Not yet dead—not yet dead?" he crept to an obscure
corner of the cellar, and opened a door that led by a ladder to the
floor of the back parlour, where there was a trap door, under which
the large table usually stood, and which he could open from below.
In the parlour Todd got a light, and feeling then still disturbed about
the groan that he had heard below, he armed himself with an iron
bar that belonged to the outer door, and with this in his right hand,
and the light in his left, he crept back again to the cellar.
A glance at the two men who lay there was sufficient to satisfy him
that they were no more; and after then taking from them a couple
of pairs of pistols, and a small sum of money, he crept back again to
the parlour. As he did so, he heard St. Dunstan's clock strike the
hour of four.
"Four!" he said. "Four. It will not be light for nearly two hours yet,
and I may rest myself awhile and think. Yes, it is necessary now that
I should think; for I have time—a little time—to do so, and much,
oh, so much to think of. There's some of my own brandy, too, in the
parlour, that's a comfort."
The fire was still burning in the parlour grate. Todd raked the
glowing embers together with the iron bar, and then he took a good
draught at the brandy. It revived him most wonderfully, and he gave
one of his old chuckles, as he muttered—
"Oh, that I could get a few whom I could name in such a position as
I had yon man in in the cellar a short time since. That would be well,
indeed. Ha! I am, after all, rather lucky, though."
A sharp knock come, at this moment, at the outer door of the shop,
and Todd sprang in alarm to his feet.
CHAPTER CXLIX.
TODD IS IN GREAT PERIL IN THE EARLY MORNING
IN LONDON.

The silence that ensued after that knock at his door, for he had
become to consider it as his again, was like the silence of the grave.
The only sound that Todd heard then, was the painful beating of his
own heart.
The guilty man was full of the most awful apprehensions.
"What is it?" he said. "Who is it?—who can it be? Surely, no one for
me. There is no one who saw me. No—no! It cannot be. It is some
accidental sound only. I—begin—to doubt if it were a knock at all.—
Oh, no, it was no knock."
Bang! came the knock again.
Todd actually started and uttered a cry of terror, and then he
crouched down and crept towards the door. He might, to be sure,
have made his escape from the premises, with some little trouble, by
the way he had got into them; but he was most anxious to find out
who it was that demanded admittance to the old shop in Fleet
Street, with all its bad associations and character of terror; so he
crept towards the door, and just as he reached it, the knock came
again.
If the whole of his future hopes—we allude to the future that might
be for him in this world only, for Todd had no hopes nor thoughts of
another—had depended upon his preserving silence and stillness, he
could not have done so, and he gave another start.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

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


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

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


personal growth every day!

ebookbell.com

You might also like