100% found this document useful (8 votes)
379 views

[Ebooks PDF] download Java Programming Exercises Volume One Language Fundamentals and Core Concepts 1st Edition Christian Ullenboom full chapters

One

Uploaded by

alzaidmbazo
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 (8 votes)
379 views

[Ebooks PDF] download Java Programming Exercises Volume One Language Fundamentals and Core Concepts 1st Edition Christian Ullenboom full chapters

One

Uploaded by

alzaidmbazo
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/ 50

Download the full version of the ebook at ebookname.

com

Java Programming Exercises Volume One Language


Fundamentals and Core Concepts 1st Edition
Christian Ullenboom

https://ebookname.com/product/java-programming-exercises-
volume-one-language-fundamentals-and-core-concepts-1st-
edition-christian-ullenboom/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookname.com


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

Programming Language Design Concepts 1st Edition Findlay

https://ebookname.com/product/programming-language-design-
concepts-1st-edition-findlay/

ebookname.com

Effective Java Programming Language Guide 1st Edition


Joshua Bloch

https://ebookname.com/product/effective-java-programming-language-
guide-1st-edition-joshua-bloch/

ebookname.com

Java programming comprehensive concepts and techniques 3rd


Edition Gary B. Shelly

https://ebookname.com/product/java-programming-comprehensive-concepts-
and-techniques-3rd-edition-gary-b-shelly/

ebookname.com

Blood Noir Anita Blake Vampire Hunter 16 1st Edition


Laurell K. Hamilton

https://ebookname.com/product/blood-noir-anita-blake-vampire-
hunter-16-1st-edition-laurell-k-hamilton/

ebookname.com
Surgical Anatomy and Techniques to the Spine 2nd Edition
Daniel H. Kim Et Al.

https://ebookname.com/product/surgical-anatomy-and-techniques-to-the-
spine-2nd-edition-daniel-h-kim-et-al/

ebookname.com

Multicultural Psychology 6th Edition Jeffery Scott Mio

https://ebookname.com/product/multicultural-psychology-6th-edition-
jeffery-scott-mio/

ebookname.com

Electrical insulation for rotating machines 1st Edition


Greg Stone

https://ebookname.com/product/electrical-insulation-for-rotating-
machines-1st-edition-greg-stone/

ebookname.com

Pauline Frommer s Washington D C Pauline Frommer Guides


1st Edition James T. Yenckel

https://ebookname.com/product/pauline-frommer-s-washington-d-c-
pauline-frommer-guides-1st-edition-james-t-yenckel/

ebookname.com

Organizational Behaviour 1st Edition Daniel King

https://ebookname.com/product/organizational-behaviour-1st-edition-
daniel-king/

ebookname.com
The Heroic Slave A Cultural and Critical Edition Frederick
Douglass (Editor)

https://ebookname.com/product/the-heroic-slave-a-cultural-and-
critical-edition-frederick-douglass-editor/

ebookname.com
Java Programming Exercises
Take the first step in raising your coding skills to the next level, and test your Java knowledge on tricky
programming tasks, with the help of the pirate Captain CiaoCiao. This is the first of two volumes which
provide you with everything you need to excel in your Java journey, including tricks that you should know
in detail as a professional, as well as intensive training for clean code and thoughtful design that carries
even complex software.

Features:

• About 200 tasks with commented solutions on different levels


• For all paradigms: object‑oriented, imperative, and functional
• Clean code, reading foreign code, and object‑oriented modeling

With numerous best practices and extensively commented solutions to the tasks, these books provide the
perfect workout for professional software development with Java.
Java Programming Exercises
Volume One: Language Fundamentals and
Core Concepts

Christian Ullenboom
Designed cover image: Mai Loan Nguyen Duy, Rheinwerk Verlag GmbH

First edition published 2025


by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431

and by CRC Press


4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

CRC Press is an imprint of Taylor & Francis Group, LLC

©2023 Christian Ullenboom. First published in the German language under the title “Captain CiaoCiao erobert Java”
(ISBN 978‑3‑8362‑8427‑1) by Rheinwerk Verlag GmbH, Bonn, Germany.

Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot
assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize to
copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been
acknowledged please write and let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or
utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including
photocopying, microfilming, and recording, or in any information storage or retrieval system, without written
permission from the publishers.

For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the
Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978‑750‑8400. For works that are
not available on CCC please contact [email protected]

Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for
identification and explanation without intent to infringe.

ISBN: 978‑1‑032‑59397‑5 (hbk)


ISBN: 978‑1‑032‑57984‑9 (pbk)
ISBN: 978‑1‑003‑45450‑2 (ebk)

DOI: 10.1201/9781003454502

Typeset in Times
by codeMantra

Access the Support Material: https://routledge.com/9781032579849


Contents

About the Author xv

Introduction 1
Previous Knowledge and Target Audience 1
Working with This Book 2
The Suggested Solutions 2
Use of This Book 3
Required Software 3
Used Java Version in the Book 4
JVM 4
Development Environment 4
Conventions 4
Helping Captain CiaoCiao and Bonny Brain 5

1 Introduction to the Java Ecosystem 6


Bytecode and JVM 6
Porting Java Programs ⭑ 6
Tools for Java Developers 7
Get to Know Error Messages of the IDE ⭑ 7
Suggested Solutions 8
Porting Java Programs ⭑ 8
Get to Know Error Messages of the IDE ⭑ 8

2 Imperative Programming 9
Screen Output 9
Learn about the SVG Specification 9
Write an SVG Circle on the Console ⭑ 10
Variables and Data Types 11
Access Variables and Output Their Assignments ⭑ 12
Quiz: Value Ranges ⭑ 12
Quiz: Does This Add Up? ⭑⭑⭑ 12
Generate Random Circles ⭑ 13
Quiz: Dazed and Confused ⭑ 14
Process User Input ⭑ 14
Expressions, Operands, and Operators 14
Quiz: Check In-Between ⭑ 14
Check If Loot Can Be Shared Fairly ⭑ 15
Do Two Numbers Share the Same Digit? ⭑⭑ 15
Convert Currency Amount to Coins ⭑⭑ 15
One Bottle of Rum, Ten Bottles of Rum ⭑ 16
Quiz: The Zero Effect ⭑ 17

v
vi Contents

Control Flow 18
Payday ⭑ 18
Quiz: Wrong Branching ⭑ 18
Convert Liters ⭑⭑ 19
Create SVG Circles with Random Colors ⭑ 19
Quiz: To Which Block Does the Else Belong? ⭑⭑ 20
Quiz: Recognize Negative Days and Hours ⭑ 20
Evaluate Input Strings for Approval ⭑ 20
Rewrite Switch Statement to Switch Expression ⭑ 21
Loops 21
Create Rotated SVG Rectangles ⭑ 21
Create SVG‑Pearl‑Chain ⭑ 22
Sum Numbers from the Command Line ⭑ 23
Go through a Mathematical Phenomenon ⭑ 24
Quiz: How Many Stars? ⭑ 24
Calculate Products for Faculties ⭑ 25
Determine If a Number Is Formed by Factorial ⭑ 25
Find the Smallest and Largest Digit of a Number ⭑ 26
Quiz: Not Like This from 1 to 100 ⭑⭑ 27
A Flag in the Wind through Nested Loops ⭑ 28
Output Simple Chessboard ⭑ 28
It’s Christmastime: Displaying Trees with Ornaments ⭑ 29
Draw Fishy Stitching Motifs ⭑ 30
Trying Instead of Thinking ⭑⭑ 31
Get the Number of Digits of a Number ⭑⭑ 32
Methods 33
Drawing Hearts ⭑ 33
Implement Overloaded Line Methods ⭑ 34
Standing Straight ⭑ 34
Create a Multiplication Table ⭑ 35
Cistercian Numerals Script ⭑⭑⭑ 36
Quiz: What Does Ding‑Dong Do? (Recursion) ⭑⭑ 37
Quiz: Repdigit (Recursion) ⭑⭑ 37
Calculate Collatz Sequence (Recursion) ⭑ 38
Ancient Egyptian Multiplication (Recursion) ⭑⭑ 38
Suggested Solutions 40
Write an SVG Circle on the Console ⭑ 40
Access Variables and Output Their Assignments 41
Quiz: Value Ranges 42
Quiz: Does This Add Up? 43
Generate Random Circles 43
Quiz: Dazed and Confused 44
Process User Input 44
Quiz: Check In-Between 44
Check If Loot Can Be Shared Fairly 45
Do Two Numbers Share the Same Digit? 45
Convert Currency Amount to Coins 46
One Bottle of Rum, Ten Bottles of Rum 47
Quiz: The Zero Effect 47
Payday 47
Quiz: Wrong Branching 48
Contents vii

Convert Liters 48
Create SVG Circles with Random Colors 49
Quiz: To Which Block Does the Else Belong? 50
Quiz: Recognize Negative Days and Hours 50
Evaluate Input Strings for Approval 51
Rewrite Switch Statement to Switch Expression 52
Create Rotated SVG Rectangles 52
Create SVG‑Pearl‑Chain 53
Sum Numbers from the Command Line 53
Go through a Mathematical Phenomenon 54
Quiz: How Many Stars? 55
Calculate Products for Faculties 55
Determine If a Number Is Formed by Factorial 57
Find the Smallest and Largest Digit of a Number 58
Quiz: Not Like This from 1 to 100 58
A Flag in the Wind through Nested Loops 59
Output Simple Chessboard 60
It’s Christmastime: Displaying Trees with Ornaments 60
Draw Fishy Stitching Motifs 61
Trying Instead of Thinking 62
Get the Number of Digits of a Number 63
Drawing Hearts 65
Implement Overloaded Line Methods 65
Standing Straight 66
Create a Multiplication Table 68
Cistercian Numerals Script 69
Quiz: What Does Ding‑Dong Do? (Recursion) 72
Quiz: Repdigit (Recursion) 72
Calculate Collatz Sequence (Recursion) 73
Ancient Egyptian Multiplication (Recursion) 75

3 Classes, Objects, and Packages 78


Creating Objects 78
Draw Polygons ⭑ 78
Working with References 80
Quiz: The Short Life of Points ⭑ 80
Build Triangles ⭑ 80
Quiz: == vs. equals(…) ⭑ 81
Quiz: Protect against NullPointerException ⭑ 81
Suggested Solutions 82
Draw Polygons 82
Quiz: The Short Life of Points 83
Build Triangles 83
Quiz: == vs. equals(…) 84
Quiz: Protect against NullPointerException 84
Note 85

4 Arrays 86
Everything Has a Type 86
Quiz: Array Types ⭑ 86
One‑Dimensional Arrays 87
viii Contents

Loop Arrays and Output Wind Speed, Wind Direction ⭑ 87


Detect Continuous Revenue Growth ⭑ 88
Array of Points ⭑ 88
Search Consecutive Strings and Determine If Salty Snook Is Coming ⭑ 89
Reverse an Array ⭑ 89
Find the Nearest Cinema ⭑⭑ 90
Raid the Candy Store and Share Fairly ⭑⭑ 90
Enhanced for Loop 91
Numbers Well Shuffled ⭑⭑ 92
Draw Mountains ⭑⭑ 93
Two‑ and Multidimensional Arrays 94
Check Mini‑Sudoku for Valid Solution ⭑⭑ 94
Enlarge Image ⭑⭑ 95
Variable Argument Lists 96
Create SVG Polygons with a Variable Number of Coordinates ⭑ 96
Check for Approval ⭑ 97
Help, Tetraphobia! Put All Fours Last ⭑⭑ 97
The Utility Class Arrays 98
Quiz: Copy Arrays ⭑ 98
Quiz: Compare Arrays ⭑ 98
Suggested Solutions 99
Quiz: Array Types 99
Loop Arrays and Output Wind Speed, Wind Direction 99
Reverse an Array 100
Array of Points 101
Search Consecutive Strings and Determine if Salty Snook is Coming 102
Reverse an Array 103
Find the Nearest Cinema 104
Raid the Candy Store and Share Fairly 105
Draw Mountains 106
Check Mini‑Sudoku for Valid Solution 107
Enlarge Image 109
Create SVG Polygons with Variable Number of Coordinates 109
Check for Approval 110
Help, Tetraphobia! Put All Fours Last 111
Quiz: Copy Arrays 112
Quiz: Compare Arrays 112

5 Character and String Processing 114


The String Class and Its Members 114
Quiz: Is String a Built-In Keyword? ⭑ 114
Building HTML Elements with Simple Concatenation ⭑ 114
Check Safe Transmission by Doubling Characters ⭑ 115
Swap Y and Z ⭑ 116
Give Defiant Answers ⭑ 117
Quiz: String Comparisons with == and Equals(…) ⭑ 117
Quiz: Is Equals(…) Symmetric? ⭑ 118
Test Strings for Palindrome Property ⭑ 118
Check if Captain CiaoCiao is in the Middle ⭑ 119
Find the Shortest Name in the Array ⭑ 120
Count String Occurrences ⭑ 120
Contents ix

Determine the Larger Crew Size ⭑ 121


Build Diamonds ⭑⭑ 122
Check for a Good Password ⭑ 123
Bake Peanut Butter Cookies ⭑⭑ 123
Calculate Sum of Digits ⭑ 124
Decolumnize Texts ⭑⭑ 125
Draw a Meadow with Favorite Flowers ⭑⭑ 126
Detect Repetitions ⭑⭑⭑ 128
Constrain Line Boundaries and Wrap Lines ⭑⭑ 128
Quiz: How Many String Objects? ⭑ 129
Test If the Fruit Is Wrapped in Chocolate ⭑⭑ 129
From Top to Bottom, from Left to Right ⭑⭑⭑ 130
Dynamic Strings with StringBuilder 131
Fill Strings ⭑ 131
Practicing the Alphabet with a Parrot ⭑ 132
Quiz: Lightly Attached ⭑ 133
Convert Number to Textual Unary Encoding ⭑ 133
Lose Weight by Moving Digits ⭑ 134
Remove Vowels ⭑ 135
Don’t Shoot the Messenger ⭑ 136
Compress Repeated Spaces ⭑⭑ 137
Insert and Remove Crackles and Pops ⭑ 137
Split CamelCase Strings ⭑ 138
Underline Words ⭑⭑ 138
Implement Caesar Encryption ⭑⭑⭑ 138
Suggested Solutions 140
Quiz: Is String a Built‑In Keyword? 140
Building HTML Elements with Simple Concatenation 140
Check Safe Transmission by Doubling Characters 140
Swap Y and Z 141
Give Defiant Answers 143
Quiz: String Comparisons with == and Equals(…) 143
Quiz: Is Equals(…) Symmetric? 143
Test Strings for Palindrome Property 144
Check if Captain CiaoCiao is in the Middle 146
Find the Shortest Name in the Array 146
Count String Occurrences 147
Determine the Larger Crew Size 148
Build Diamonds 149
Check for a Good Password 151
Bake Peanut Butter Cookies 152
Calculate Sum of Digits 153
Decolumnize Texts 154
Draw a Meadow with Favorite Flowers 156
Detect Repetitions 158
Constrain Line Boundaries and Wrap Lines 159
Quiz: How Many String Objects? 160
Test if the Fruit is Wrapped in Chocolate 160
From Top to Bottom, from Left to Right 161
Fill Strings 162
Practicing the Alphabet with a Parrot 163
x Contents

Quiz: Lightly Attached 164


Convert Number to Textual Unary Encoding 165
Lose Weight by Moving Digits 166
Remove Vowels 167
Don’t Shoot the Messenger 169
Compress Repeated Spaces 170
Insert and Remove Crackles and Pops 171
Split CamelCase Strings 172
Underline Words 173
Implement Caesar Encryption 174

6 Writing Your Own Classes 176


Class Declaration and Object Properties 177
Declare Radio with Instance Variables and a Main Program ⭑ 177
Implementing Methods of a Radio ⭑ 177
Private Parts: Make Instance Variables Private ⭑ 178
Create Setters and Getters ⭑ 178
Static Variables Methods 178
Convert Station Names to Frequencies ⭑ 178
Write Log Output with a Tracer Class ⭑ 179
Quiz: Nothing Stolen ⭑ 180
Simple Enumerations 181
Give Radio an AM–FM Modulation ⭑ 181
Set Valid Start and End Frequency for Modulation ⭑ 181
Constructors 181
Writing Radio Constructors ⭑ 182
Implement Copy Constructor ⭑ 182
Realize Factory Methods ⭑ 182
Associations 183
Connect Monitor Tube with TV ⭑ 183
Quiz: Association, Composition, and Aggregation ⭑ 184
Add Radios with a 1:n Association to the Ship ⭑⭑ 184
Inheritance 185
Introduce Abstraction into Electrical Devices via Inheritance ⭑ 185
Quiz: Three, Two, and One ⭑ 185
Quiz: Private and Protected Constructor ⭑ 186
Determine the Number of Switched on Electrical Devices ⭑ 186
Ship Should Hold Any Electronic Device ⭑ 186
Take Working Radios on the Ship ⭑ 187
Solve Equivalence Test with Pattern Variable ⭑ 187
Fire Alarm Does Not Go Off: Overriding Methods ⭑ 188
Calling the Methods of the Superclass ⭑⭑ 188
Polymorphism and Dynamic Binding 189
Holiday! Switch Off All Devices ⭑ 189
The Big Move ⭑ 190
Quiz: Bumbo Is a Great Drink ⭑⭑ 191
Quiz: Vodka with Taste ⭑ 192
Quiz: Rum‑Paradise ⭑⭑ 192
Abstract Classes and Abstract Methods 192
Quiz: Consumer Devices as an Abstract Superclass? ⭑ 193
TimerTask as an Example for an Abstract Class ⭑⭑ 193
Contents xi

Suggested Solutions 194


Declare Radio with Instance Variables and a Main Program 194
Implementing Methods of a Radio 195
Private Parts: Make Instance Variables Private 196
Create Setters and Getters 197
Convert Station Names to Frequencies 198
Write Log Output with a Tracer Class 198
Quiz: Nothing Stolen 199
Give Radio an AM–FM Modulation 199
Set Valid Start and End Frequency for Modulation 200
Writing Radio Constructors 201
Implement Copy Constructor 202
Realize Factory Methods 202
Connect Monitor Tube with TV 204
Quiz: Association, Composition, and Aggregation 205
Add Radios with a 1:n Association to the Ship 205
Introduce Abstraction into Electrical Devices via Inheritance 206
Quiz: Three, Two, and One 207
Quiz: Private and Protected Constructor 208
Determine Number of Switched on Electrical Devices 208
Ship Should Hold Any Electronic Device 209
Take Working Radios on the Ship 209
Solve Equivalence Test with Pattern Variable 210
Fire Alarm Does Not Go Off: Overriding Methods 210
Calling the Methods of the Superclass 211
Holiday! Switch Off All Devices 212
The Big Move 212
Quiz: Bumbo Is a Great Drink 212
Quiz: Vodka with Taste 213
Quiz: Rum‑Paradise 213
Quiz: Consumer Devices as an Abstract Superclass? 214
TimerTask as an Example for an Abstract Class 214
Note 215

7 Records, Interfaces, Enumerations, and Sealed Classes 216


Records 216
Quiz: Which Statements Are True for Records? ⭑ 216
Develop Record for Complex Numbers ⭑ 216
Quiz: Records with Static Variables ⭑ 217
Record Patterns ⭑ 217
Interfaces 218
Compare Consumption of Electrical Devices ⭑ 218
Find Electronic Devices with the Highest Power Consumption ⭑ 219
Use Comparator Interface for Sorting ⭑ 220
Static and Default Methods in Interfaces ⭑⭑⭑ 220
Delete Selected Elements with Predicate ⭑⭑ 220
Enumeration Types (enum) 221
Enumeration for Candy ⭑ 221
Deliver Random Candies ⭑ 222
Tagging Candy with Addictive Value ⭑⭑ 223
Interface Implementations via an enum ⭑⭑ 224
xii Contents

Quiz: Aviso and Brig ⭑ 225


Suggested Solutions 225
Quiz: Which Statements Are True for Records? 225
Quiz: Records with Static Variables 226
Quiz: Records with Static Variables 227
Compare Consumption of Electrical Devices 228
Find Electronic Devices with the Highest Power Consumption 229
Use Comparator Interface for Sorting 230
Static and Default Methods in Interfaces 230
Delete Selected Elements with Predicate 231
Enumeration for Candy 232
Deliver Random Candies 233
Tagging Candy with Addictive Value 233
Interface Implementations via an enum 236
Quiz: Aviso and Brig 237

8 Nested Types 238


Declare Nested Types 238
Set AM–FM Modulation to Radio Type ⭑ 238
Write Three Kinds of Watt‑Comparator Implementations ⭑ 239
Nested Types Quiz 239
Quiz: Pirate Could Have Waved ⭑ 239
Quiz: Name in a Bottle ⭑⭑ 240
Quiz: Get Me Another Bottle of Rum ⭑ 240
Suggested Solutions 241
Set AM–FM Modulation to Radio Type 241
Write Three Kinds of Watt‑Comparator Implementations 242
Quiz: Pirate Could Have Waved 243
Quiz: Name in a Bottle 243
Quiz: Get Me another Bottle of Rum 243

9 Exception Handling 244


Catching Exceptions 244
Get the Longest Line of a File ⭑ 244
Identify Exceptions, Laughing All the Time ⭑ 245
Convert String Array to Int Array and Be Lenient on Nonnumbers ⭑ 245
Quiz: And Finally ⭑ 246
Quiz: A Lonely Try ⭑ 246
Quiz: Well Caught ⭑ 246
Quiz: Too Much of a Good Thing ⭑ 247
Quiz: Try‑Catch in Inheritance ⭑⭑ 247
Throwing Custom Exceptions 247
Quiz: Throw and Throws ⭑ 247
Quiz: The Division Fails ⭑ 248
Writing Your Own Exception Classes 248
Show Impossible Watt with Own Exception ⭑ 248
Quiz: Potatoes or Other Vegetables ⭑ 248
Try‑with‑Resources 249
Write Current Date to File ⭑ 249
Read Notes and Write Them to a New ABC File ⭑⭑ 249
Contents xiii

Quiz: Excluded ⭑ 250


Suggested Solutions 251
Get the Longest Line of a File 251
Identify Exceptions, Laughing All the Time 252
Convert String Array to Int Array and Be Lenient on Nonnumbers 254
Quiz: And Finally 255
Quiz: A Lonely Try 255
Quiz: Well Caught 256
Quiz: Too Much of a Good Thing 256
Quiz: Try‑Catch in Inheritance 257
Quiz: Throw and Throws 257
Quiz: The Division Fails 257
Show Impossible Watt with Own Exception 258
Quiz: Potatoes or Other Vegetables 260
Write Current Date to File 260
Read Notes and Write Them to a New ABC File 261
Quiz: Excluded 262

10 Lambda Expressions and Functional Programming 263


Lambda Expressions 264
Quiz: Recognize Valid Functional Interfaces ⭑ 264
Quiz: From Interface Implementation to Lambda Expression ⭑ 264
Write Lambda Expressions for Functional Interfaces ⭑ 265
Quiz: Write Lambda Expressions Like This? ⭑ 266
Developing Lambda Expressions ⭑ 266
Quiz: Contents of the Package java.util.function ⭑ 266
Quiz: Know Functional Interfaces for Mappings ⭑ 266
Method and Constructor References 268
Rewriting Lambda Expressions ⭑⭑ 268
Selected Functional Interfaces 268
Delete Entries, Remove Comments, Convert to CSV ⭑ 268
Suggested Solutions 269
Quiz: Recognize Valid Functional Interfaces 269
Quiz: From Interface Implementation to Lambda Expression 270
Write Lambda Expressions for Functional Interfaces 271
Quiz: Write Lambda Expressions Like This? 271
Developing Lambda Expressions 271
Quiz: Contents of the Package java.util.function 271
Quiz: Know Functional Interfaces for Mappings 272
Rewriting Lambda Expressions 273
Delete Entries, Remove Comments, and Convert to CSV 273
Note 274

11 Special Types from the Java Class Library 275


Absolute Superclass java.lang.Object 275
Generate equals(Object) and hashCode() ⭑ 276
Existing equals(Object) Implementations ⭑⭑ 276
Interfaces Comparator and Comparable 277
Quiz: Natural Order Or Not? ⭑ 277
Handle Superheroes 277
xiv Contents

Compare Superheroes ⭑⭑ 279


Concatenate Hero Comparators ⭑ 280
Using a Key Extractor to Easily Create a Comparator ⭑⭑ 280
Sort Points by Distance to Center ⭑ 282
Find Stores Nearby ⭑⭑ 283
Autoboxing 283
Quiz: Handling Null Reference in Unboxing ⭑ 283
Quiz: Unboxing Surprise ⭑⭑ 284
Suggested Solutions 284
Generate equals(Object) and hashCode() 284
Existing equals(Object) Implementations 287
Quiz: Natural Order Or Not? 289
Compare Superheroes 289
Concatenate Hero Comparators 290
Using a Key Extractor to Easily Create a Comparator 291
Sort Points by Distance to Center 291
Find Stores Nearby 292
Quiz: Handling Null Reference in Unboxing 293
Quiz: Unboxing Surprise 294
Notes 294

Appendix A: Most Frequent Types and Methods in the Java Universe 295
A.1 Packages with the Most Common Types 295
A.2 100 Most Common Types 296
A.3 100 Most Common Methods 299
A.4 100 Most Common Methods Including Parameter List 302
About the Author

Christian Ullenboom started his programming journey at the tender age of ten, typing his first lines of
code into a C64. After mastering assembler programming and early BASIC extensions, he found his call‑
ing on the island of Java, following his studies in computer science and psychology. Despite indulging in
Python, JavaScript, TypeScript, and Kotlin vacations, he remains a savant of all things Java.
For over 20 years, Ullenboom has been a passionate software architect, Java trainer (check out http://
www.tutego.com), and IT specialist instructor. His expertise has resulted in a number of online video
courses and reference books:

• Java: The Comprehensive Guide (ISBN‑13: 978‑1493222957)


• Spring Boot 3 and Spring Framework 6 (ISBN‑13: 978‑1493224753)
• Java ist auch eine Insel: Java programmieren lernen mit dem umfassenden Standardwerk für
Java‑Entwickler (ISBN‑13: 978‑3836287456)
• Java SE 9 Standard‑Bibliothek: Das Handbuch für Java‑Entwickler (ISBN‑13: 978‑3836258746)
• Captain CiaoCiao erobert Java: Das Trainingsbuch für besseres Java (ISBN‑13:
978‑3836284271)

Christian Ullenboom has been spreading Java love through his books for years, earning him the coveted
title of Java Champion from Sun (now Oracle) way back in 2005. Only a select few—about 300 world‑
wide—have achieved this status, making him a true Java superstar.
As an instructor, Ullenboom understands that learning by doing is the most effective way to master a
skill. So, he has compiled a comprehensive catalog of exercises that accompany his training courses. This
book features a selection of those exercises, complete with documented solutions.
His roots are in Sonsbeck, a small town in the Lower Rhine region of Germany.

xv
Introduction

Many beginners in programming often ask themselves, “How can I strengthen my skills as a developer?
How can I become a better programmer?” The answer is simple: study, attend webinars, learn, repeat,
practice, and discuss your work with others. Many aspects of programming are similar to learning new
skills. Just as a book can’t teach you how to play a musical instrument, watching the Fast and the Furious
movie series won’t teach you how to drive. The brain develops patterns and structures through repeated
practice. Learning a programming language and a natural language have many similarities. Consistent
use of the language and the desire and need to express and communicate in it (just as you need to do so to
order a burger or a beer) lead to gradual improvement in skills.
Books and webinars on learning a programming language are available, but reading, learning,
practicing, and repeating are just one aspect of becoming a successful software developer. To cre‑
ate effective software solutions, you need to creatively combine your knowledge, just as a musician
regularly practices finger exercises and maintains their repertoire. The more effective your exercises
are, the faster you will become a master. This book aims to help you progress and gain more hands‑on
experience.
Java 21 declares more than 2,300 classes, about 1,400 interfaces, close to 140 enumerations, around
50 exceptions, and a few annotation types and records are included as well. However, only a fraction of
these types are relevant in practice. This book selects the most important types and methods for tasks,
making them motivating and following Java conventions. Alternative solutions and approaches are also
presented repeatedly. The goal is to make nonfunctional requirements clear because the quality of pro‑
grams is not just about “doing what it should”. Issues such as correct indentation, following naming con‑
ventions, proper use of modifiers, best practices, and design patterns are essential. The proposed solutions
aim to demonstrate these principles, with the keyword being Clean Code.

PREVIOUS KNOWLEDGE AND TARGET AUDIENCE


The book is aimed at Java developers who are either new to Java or are already advanced and wish to learn
more about the core language features. The intended audience includes:

• Computer science students.


• IT specialists.
• Java programmers.
• Software developers.
• Job applicants.

The book is centered around tasks and fully documented solutions, with detailed explanations of Java
peculiarities, good object‑oriented programming practices, best practices, and design patterns. The
exercises are best solved with a textbook, as this exercise book is not a traditional textbook. A useful
approach is to work through a topic with a preferred textbook before attempting the exercises that cor‑
respond to it.

DOI: 10.1201/9781003454502-1 1
2 Java Programming Exercises

The first set of tasks is designed for programming beginners who are new to Java. As you gain more
experience with Java, the tasks become more challenging. Therefore, there are tasks for both beginners
and advanced developers.
Additionally, this book does not require the use of tools like profiling tools, as these are beyond the
scope of this book.

WORKING WITH THIS BOOK


The task book is organized into different sections. The first section covers the Java language, followed
by selected areas of the Java standard library, such as data structures or file processing. Each area is
accompanied by programming tasks and “quiz” questions that contain surprises. Each section starts with
a small motivation and characterization of the topic, followed by the exercises. Additional tips and hints
are provided for particularly challenging assignments, while other exercises offer optional extensions for
further exploration.
The majority of exercises are independent of each other, making it easy for readers to dive in
anywhere. However, in the chapter on imperative programming, some tasks build on each other to
develop a larger program, and the same goes for the chapter on object‑oriented programming. The
problem definitions make this clear, and more complex programs help to provide context for under‑
standing different language characteristics. Furthermore, a more complex program can motivate read‑
ers to continue.
The exercises are rated with one, two, or three stars to indicate their complexity, although this rating
is subjective to the author.

1 star ★: Simple exercises, suitable for beginners. They should be easy to solve without much
effort. Often only transfer of knowledge is required, for example, by writing down things that
are in a textbook differently.
2 stars ★★: The effort is higher here. Different techniques have to be combined. Greater creativity
is required.
3 stars ★★★: Assignments with three stars are more complex, require recourse to more prior
knowledge, and sometimes require research. Frequently, the tasks can no longer be solved with
a single method, but require multiple classes that must work together.

THE SUGGESTED SOLUTIONS


The task book provides at least one suggested solution for each problem. The term “sample solution” is
not used to avoid implying that the given solution is the best one and that all other solutions are useless.
Readers are encouraged to compare their solutions with the proposed solution and can be satisfied if
their solution is more refined. All proposed solutions are commented, making it possible to follow all
steps well.
The suggested solutions are compiled at the end of each chapter to reduce the temptation to look
into a solution directly after the task, which takes the fun out of solving the task. The suggested solu‑
tions can also be found on the website https://github.com/ullenboom/captain‑ciaociao. Some solu‑
tions ­contain comments of the type //tag::solution[], which marks the parts of the solutions printed in
the book.
 • Introduction 3

USE OF THIS BOOK


To become a software developer, you must master the art of turning problems into code, and that’s where
practice and role models come in. While there are plenty of exercises available online, they’re often
disorganized, poorly documented, and outdated. That’s where this book shines, by offering a systematic
approach to tasks and well‑thought‑out solutions. Studying these solutions and reading code in general
helps the brain develop patterns and solutions that can be applied to future coding challenges. It’s like
reading the Bible; you need to read to understand and learn. Surprisingly, many software developers
write code without bothering to read others’ code, which can lead to confusion and misunderstand‑
ing. Reading good code elevates our writing skills by building patterns and solutions that our brains
unconsciously transfer to our own code. Our brains form neuronal structures independently based on
templates, and the quality of the input we receive matters greatly. Therefore, we should only feed our
brains with good code, as bad solutions make for bad models. The book covers important topics such as
exception handling or error handling, discussing the correct input values, identifying erroneous states,
and how to handle them. In software, things can and will go wrong, and we must be prepared to deal
with the less‑than‑perfect world.
It’s easy for developers to get stuck in their ways of writing code, which is why it’s important to
explore new approaches and “expand our vocabulary”, so to speak. For Java developers, libraries are their
vocabulary, but too many enterprise Java developers write massive, non‑object‑oriented code. The solu‑
tion is to continuously improve object‑oriented modeling, which is precisely what this book demonstrates.
It introduces new methods, creates new data types, and minimizes complexity. Additionally, functional
programming is becoming increasingly important in Java development, and all solutions in this book take
advantage of modern language features.
While some solutions may appear overly complex, the tasks and proposed solutions in this book can
help developers improve their ability to concentrate and follow through with steps. In practice, the ability
to concentrate and quickly comprehend code is crucial for developers. Often, developers must join a new
team and be able to understand and modify unfamiliar source code, and possibly fix bugs. Those who
wish to expand upon existing open‑source solutions can also benefit from honing their concentration skills
through these exercises.
In addition to its emphasis on the Java programming language, syntax, libraries, and object orien‑
tation, this book provides numerous side notes on topics such as algorithms, the historical evolution of
programming, comparisons to other programming languages, and data formats. These additional insights
and perspectives offer readers a more well‑rounded understanding of software development beyond just
the technical aspects.
If you’re looking for one more reason to add this book to your collection, it doubles as a fantastic
sleep aid!

REQUIRED SOFTWARE
While solving a task with just a pen and paper is possible in theory, modern software development requires
the proper use of tools. Knowing programming language syntax, object‑oriented modeling, and libraries
is just the tip of the iceberg. Understanding the JVM (Java Virtual Machine), using tools like Maven and
Git for version management, and becoming proficient in an IDE (Integrated Development Environment)
are all crucial aspects of professional software development. Some developers can even perform magic in
their IDE, generating code and fixing bugs automatically.
4 Java Programming Exercises

USED JAVA VERSION IN THE BOOK


While Java version 8 remains still strong in enterprise settings, it’s crucial for learners to become acquainted
with the latest language features. Accordingly, whenever feasible, the suggested solutions in this book
leverage Java 21. Not only is this version equipped with long‑term support (LTS), but runtime environment
providers also offer extensive support, ensuring that the release retains its relevance for an extended period.

JVM
If we want to run Java programs, we need a JVM. In the early days, this was easy. The runtime environ‑
ment first came from Sun Microsystems, later from Oracle, which took over Sun. Today, it is much more
confusing. Although a runtime environment can still be obtained from Oracle, the licensing terms have
changed, at least for Java 8 up to Java 16. Testing and development are possible with the Oracle JDK,
but not in production. In this case, Oracle charges license fees. As a consequence, various institutions
compile their own runtime environments from the OpenJDK, the original sources. The best known are
Eclipse Adoptium (https://adoptium.net/), Amazon Corretto (https://aws.amazon.com/de/corretto), Red
Hat OpenJDK (https://developers.redhat.com/products/openjdk/overview), and others such as those from
Azul Systems or Bellsoft. There is no specific distribution that readers are required to follow.

Development Environment
Java source code is just plain text, so technically a simple text editor is all you need. However, relying solely
on Notepad or vi for productivity is like trying to win a race on a tricycle. Modern integrated development
environments support us with many tasks: color highlighting of keywords, automatic code completion,
intelligent error correction, insertion of code blocks, visualization of states in the debugger, and much more.
It is therefore advisable to use a full development environment. Four popular IDEs are: IntelliJ, Eclipse,
Visual Studio Code, and (Apache) NetBeans. Just like with Java runtime environments, the choice of IDE
is left to the reader. Eclipse, NetBeans, and Visual Studio Code are all free and open‑source, while IntelliJ
Community Edition is also free, but the more advanced IntelliJ Ultimate Edition will cost you some cash.
Halfway through the book, we delve into implementing project dependencies using Maven in a few
places.

CONVENTIONS
Code is written in fix width font, filenames are italicized. To distinguish methods from attributes,
methods always have a pair of parentheses, such as in “the variable max contains the maximum” or “it
returns max() the maximum”. Since methods can be overloaded, either the parameter list is named, as in
equals(Object), or an ellipsis abbreviates it, such as in “various println(…) methods”. If a group
of identifiers is addressed, * is written, like print*(...) prints something on the screen.
In the suggested solutions, there are usually only the relevant code snippets, so as not to blow up the
book volume. The name of the file is mentioned in the listing caption, like this:
VanillaJava.java

class VanillaJava { }
 • Introduction 5

Sometimes, we need to flex our terminal muscles and execute programs from the command line (also
known as console or shell). Since each command‑line program has its own prompt sequence, it is symbol‑
ized here in the book with a $. Example:

$ java ‑version
openjdk version "21.0.1" 2023‑10‑17
OpenJDK Runtime Environment (build 21.0.1+12‑29)
OpenJDK 64‑Bit Server VM (build 21.0.1+12‑29, mixed mode, sharing)

If the Windows command line is explicitly meant, the prompt character > is set:

> netstat –e
Interface Statistics

Received Sent

Bytes 218927776 9941980


Unicast packets 162620 64828
Non‑unicast packets 276 668
Discards 0 0
Errors 0 0
Unknown protocols 0

HELPING CAPTAIN CIAOCIAO AND BONNY BRAIN


Ahoy there! Once upon a time, Captain CiaoCiao and Bonny Brain lent ye a hand with a certain matter
we won’t speak of. And now, ye owe them a favor. But fear not, for it will be worth yer while to assist
them on their latest venture. Join the daring duo and their loyal crew as they sail the seven seas, striking
deals with unsavory characters across the globe. Their secret hideout is on the island of Baloo, where the
currency of choice is Liretta.
Introduction to the
Java Ecosystem 1
Many newcomers get caught in “tutorial hell”: they read a lot, watch countless videos. This chapter is here
to help you break out of your shell and get comfortable with practical programming. You’ll not only learn
your way around the development environment, but you’ll also be able to flex your skills by running pro‑
grams from the command line. In the process, we will get to know our development environment better,
be able to run programs from the command line, and see more clearly the division of tasks between the
Java compiler and the runtime environment.
Prerequisites

• Understand the task of Java compiler, bytecode, and JVM.


• Be able to compile Java programs on the command line.
• Know the difference between java and javac programs.
• Set up and be able to operate Java development environment.

BYTECODE AND JVM


In the early days of Java, the usual way for compilers was to generate a directly executable machine file.
Sun Microsystems wanted something different: a platform‑independent programming language—this led
to Java. To achieve this, the compiler is no longer allowed to generate machine code, but the Java com‑
piler generates bytecode. This bytecode is not bound to a machine. So that the bytecode can be executed,
a runtime environment and a function library must exist, called Java Runtime Environment (short JRE).
Part of the JRE is the Java Virtual Machine, short JVM, which executes the bytecode.

Porting Java Programs ⭑


Anyone starting in programming is bound to have come across a classic: the Hello World output. In the
mid‑1970s, this small example appeared in a C tutorial and has since been ported to various programming
languages. Although the program is small, it serves an important purpose: to test whether all the develop‑
ment tools are installed and working correctly.
Task:
Save the following program named Application.java. Pay attention to the upper/lower case.
Application.java

public class Application {


public static void main( String[] args ) {
System.out.println( "Aye Captain!" );
}
}

6 DOI: 10.1201/9781003454502-2
1 • Introduction to the Java Ecosystem 7

We can now compile the program with

$ javac Application.java

and start it with

$ java Application

Question:

• Would it be possible to copy the file Application.class from a Windows operating system
to a Linux operating system and java can run the program?
• What software must be installed on the computer?

TOOLS FOR JAVA DEVELOPERS


The choice of development environment often depends on personal taste, and they all handle the core
tasks well:

• IntelliJ.
• Eclipse.
• Visual Studio Code.
• (Apache) NetBeans IDE.

This workbook is completely independent of the IDE. All developers should work intensively with the
shortcuts, the debugger, and the other tools. The web pages of the developers and YouTube offer plenti‑
fully material for it, a small selection:

• Eclipse: https://help.eclipse.org/, https://www.youtube.com/user/EclipseFdn/playlists?view=


50&sort=dd&shelf_id=6
• IntelliJ: https://www.youtube.com/user/intellijideavideo

Get to Know Error Messages of the IDE ⭑


This task is about getting to know the development environment a little better.
Let’s take the following program again:
Application.java

public class Application {


public static void main( String[] args ) {
System.out.println( "Aye Captain!" );
}
}

Task:

• Transfer Application.java to the IDE.


• Deliberately build errors into the program code, and observe the error messages. Some suggestions:
8 Java Programming Exercises

• Change the file name.


• Change the case, for example, write Class instead of class.
• The main program is not started until the class has a special method public static
void main(String[] args). What happens if the method is not called main, for
example, but something else, e.g., Main or run?
• Try to output Greek letters or hearts, can you do that?
• White space is often used, so spaces (usually not a tab) and line breaks appear after each
statement. Is the following valid like this?

public class Application{public static void main(String[]args){System.


out.println("Aye Captain!");}}.

SUGGESTED SOLUTIONS

Porting Java Programs ⭑


If the Application.class file is copied from a Windows operating system to a Linux machine, it will run
there as well. To run the file, a runtime environment like Oracle JDK is always required.

Get to Know Error Messages of the IDE ⭑


You could deliberately include the following errors:

• If the class is public, the filename must be the same as the class. So, we could change the
filename or class name. The IDE recognizes the error and suggests a renaming.
• Keywords are always lowercase in Java. What happens if you capitalize a keyword like pub‑
lic or class or capitalize single letters? In that case, there is a compiler error.
• If the start method is not declared as public static void main(String[] args),
but differently, the editor cannot guess, but the compiler will translate the program correctly
because public static void run(String[] args) could, in general, be a method
we want. It is a semantic error and not a syntactic error, which the editor or the compiler can‑
not notice. But the runtime environment will throw an error that the main(…) method is not
present when the program is to be started (semantic error).
• A method consists of a sequence of statements—these statements are in a block enclosed in
curly braces. The same is true for the class, which consists of a collection of methods that must
also be placed in a block altogether. Indentations are not significant in Java. You can provoke
an error by omitting the curly braces completely.
• Every open curly bracket requires a closing curly bracket. If you omit a curly bracket, it will
cause a compiler error.
• String literals are enclosed with different symbols in different programming languages. Some
programming languages use double quotes ("), other programming languages use a single
quote ('), and some programming languages use backticks (`). Java can accept the strings only
in double quotes; otherwise, there will be compiler errors. Single quotes are used for single
characters (data type char).
• In Java, white space is used to make the source code clearer, especially to make the blocks vis‑
ible. You can save some white space. You can try to find out which of the whitespace characters
you are allowed to delete and which you are not. The code given in the task is fine.
Random documents with unrelated
content Scribd suggests to you:
CHAPTER VII
WHAT THE RED ENVELOPE HELD

“My dear Angel,” wrote Jimmy, “I commend to you one Mr. Spedding,
an ingenious man. If by chance you ever wish to visit him, do so in
business hours. If you desire to examine his most secret possession,
effect an entrance into a dreary-looking house at the corner of Cley’s
Road, a stone’s-throw from ‘High Holly Lodge.’ It is marked in plain
characters ‘To Let.’ In the basement you will find a coal-cellar.
Searching the coal-cellar diligently, you will discover a flight of stone
steps leading to a subterranean passage, which burrows under the
ground until it arrives at friend Spedding’s particular private vault. If
this reads like a leaf torn from Dumas or dear Harrison Ainsworth it is
not my fault. I visited our legal adviser last night, and had quite a
thrilling evening. That I am alive this morning is a tribute to my
caution and foreseeing wisdom. The result of my visit is this: I have
the key of the ‘safe-word’ in my hands. Come and get it.”
Angel found the message awaiting him when he reached Scotland
Yard that morning. He too had spent sleepless hours in a futile
attempt to unravel the mystery of old Reale’s doggerel verse.
A telegram brought Kathleen Kent to town. Angel met her at a quiet
restaurant in Rupert Street, and was struck by the delicate beauty of
this slim girl with the calm, gray eyes.
She greeted him with a sad little smile.
“I was afraid you would never see me again after my outburst of the
other night,” she said. “This—this—person is a friend of yours?”
“Jimmy?” asked the detective cheerily. “Oh, yes, Jimmy’s by way of
being a friend; but he deserved all you said, and he knows it, Miss
Kent.”
The girl’s face darkened momentarily as she thought of Jimmy.
“I shall never understand,” she said slowly, “how a man of his gifts
allowed himself to become——”
“But,” protested the detective, “he told you he took no part in the
decoying of your father.”
The girl turned with open-eyed astonishment.
“Surely you do not expect me to believe his excuses,” she cried.
Angel Esquire looked grave.
“That is just what I should ask you to believe,” he said quietly.
“Jimmy makes no excuses, and he would certainly tell no lie in
extenuation of his faults.”
“But—but,” said Kathleen, bewildered, “he is a thief by his own
showing—a bad man.”
“A thief,” said Angel soberly, “but not a bad man. Jimmy is a puzzle
to most people. To me he is perfectly understandable; that is
because I have too much of the criminal in my own composition,
perhaps.”
“I wish, oh, how I wish I had your faith in him! Then I could absolve
him from suspicion of having helped ruin my poor father.”
“I think you can do that,” said the detective almost eagerly. “Believe
me, Jimmy is not to be judged by conventional standards. If you ask
me to describe him, I would say that he is a genius who works in an
eccentric circle that sometimes overlaps, sometimes underreaches
the rigid circle of the law. If you asked me as a policeman, and if I
was his bitterest enemy, what I could do with Jimmy, I should say,
‘Nothing.’ I know of no crime with which I could charge him, save at
times with associating with doubtful characters. As a matter of fact,
that equally applies to me. Listen, Miss Kent. The first big
international case I figured in was a gigantic fraud on the Egyptian
Bank. Some four hundred thousand pounds were involved, and
whilst from the outsider’s point of view Jimmy was beyond suspicion,
yet we who were working at the case suspected him, and pretty
strongly. The men who owned the bank were rich Egyptians, and the
head of all was a Somebody-or-other Pasha, as great a scoundrel as
ever drew breath. It is impossible to tell a lady exactly how big a
scoundrel he was, but you may guess. Well, the Pasha knew it was
Jimmy who had done the trick, and we knew, but we dare not say so.
The arrest of Jimmy would have automatically ruined the banker.
That was where I realized the kind of man I had to deal with, and I
am always prepared when Jimmy’s name is mentioned in connection
with a big crime to discover that his victim deserved all he got, and a
little more.”
The girl gave a little shiver.
“It sounds dreadful. Cannot such a man as that employ his talents to
a greater advantage?”
Angel shrugged his shoulders despairingly.
“I’ve given up worrying about misapplied talents; it is a subject that
touches me too closely,” he said. “But as to Jimmy, I’m rather glad
you started the conversation in that direction, because I’m going to
ask you to meet him to-day.”
“Oh, but I couldn’t,” she began.
“You are thinking of what happened on the night the will was read?
Well, you must forget that. Jimmy has the key to the verse, and it is
absolutely imperative that you should be present this afternoon.”
With some demur, she consented.

In the sitting-room of Jimmy’s flat the three sat round a table littered
with odds and ends of papers.
The girl had met him with some trepidation, and his distant bow had
done more to assure her than had he displayed a desire to
rehabilitate himself in her good opinion.
Without any preliminaries, Jimmy showed the contents of the packet.
He did not explain to the girl by what means he had come into
possession of them.
“Of all these papers,” began Jimmy, tapping the letter before him,
“only one is of any service, and even that makes confusion worse
confounded. Reale had evidently had this cursed cryptogram in his
mind for a long time. He had made many experiments, and rejected
many. Here is one.”
He pushed over a card, which bore a few words in Reale’s
characteristic hand.
Angel read:—

“The word of five letters I will use, namely:


1. White every 24 sec.
2. Fixed white and red.
3. White group two every 30 sec.
4. Group occ. white red sec. 30 sec.
5. Fixed white and red.”

Underneath was written: “No good; too easy.”


The detective’s brows were bent in perplexity.
“I’m blessed if I can see where the easiness comes in,” he said. “To
me it seems so much gibberish, and as difficult as the other.”
Jimmy noted the detective’s bewilderment with a quiet smile of
satisfaction. He did not look directly at the girl, but out of the corner
of his eyes he could see her eager young face bent over the card,
her pretty forehead wrinkled in a despairing attempt to decipher the
curious document.
“Yet it was easy,” he said, “and if Reale had stuck to that word, the
safe would have been opened by now.”
Angel pored over the mysterious clue.
“The word, as far as I can gather,” said Jimmy, “is ‘smock,’ but it may
be——”
“How on earth——” began Angel in amazement.
“Oh, it’s easy,” said Jimmy cheerfully, “and I am surprised that an old
traveler like yourself should have missed it.”
“Group occ. white red sec. 30 sec.,” read Angel.
Jimmy laughed.
It was the first time the girl had seen this strange man throw aside
his habitual restraint, and she noted with an unaccountable
satisfaction that he was decidedly handsome when amused.
“Let me translate it for you,” said Jimmy. “Let me expand it into,
‘Group occulting White with Red Sectors every Thirty Seconds.’ Now
do you understand?”
Angel shook his head.
“You may think I am shockingly dense,” he said frankly, “but even
with your lucid explanation I am still in the dark.”
Jimmy chuckled.
“Suppose you went to Dover to-night, and sat at the end of the
Admiralty Pier. It is a beautiful night, with stars in the sky, and you
are looking toward France, and you see——?”
“Nothing,” said Angel slowly; “a few ships’ lights, perhaps, and the
flash of the Calais Lighthouse——”
“The occulting flash?” suggested Jimmy.
“The occ.! By Jove!”
“Glad you see it,” said Jimmy briskly. “What old Reale did was to
take the names of five famous lights—any nautical almanac will give
you them:

Sanda.
Milford Haven.
Orkneys.
Caldy Island.
Kinnaird Head.
They form an acrostic, and the initial letters form the work ‘smock’;
but it was too easy—and too hard, because there are two or three
lights, particularly the fixed lights, that are exactly the same, so he
dropped that idea.”
Angel breathed an admiring sigh.
“Jimmy, you’re a wonder,” he said simply.
Jimmy, busying himself amongst the papers, stole a glance at the
girl.
“I am very human,” he thought, and was annoyed at the discovery.
“Now we come to the more important clue,” he said, and smoothed a
crumpled paper on the table.
“This, I believe, to have a direct bearing on the verse.”
Then three heads came close together over the scrawled sheet.
“A picture of a duck, which means T,” spelt Angel, “and that’s erased;
and then it is a snake that means T——”
Jimmy nodded.
“In Reale’s verse,” he said deliberately, “there are six words; outside
of those six words I am convinced the verse has no meaning. Six
words strung together, and each word in capitals. Listen.”
He took from his pocketbook the familiar slip on which the verse was
written:—
“Here’s a puzzle in language old,
Find my meaning and get my gold.
Take one BOLT—just one, no more—
Fix it on behind a DOOR.
Place it at a river’s MOUTH
East or west or north or south.
Take some LEAVES and put them whole
In some WATER in a BOWL.
I found this puzzle in a book
From which some mighty truths were took.”
“There are six words,” said Jimmy, and scribbled them down as he
spoke:—
“Bolt (or Bolts). Leave (or Leaves).
Door. Water.
Mouth. Bowl.
Each one stands for a letter—but what letter?”
“It’s rather hopeless if the old man has searched round for all sorts of
out-of-the-way objects, and allowed them to stand for letters of the
alphabet,” said Angel.
The girl murmured something, and met Jimmy’s inquiring eyes.
“I was only saying,” she said hesitatingly, “that there seems to be a
method in all this.”
“Except,” said Jimmy, “for this,” and he pointed to the crossed-out
duck. “By that it would seem that Reale chose his symbols
haphazard, and that the duck not pleasing him, he substituted the
snake.”
“But,” said Kathleen, addressing Angel, “doesn’t it seem strange that
an illiterate man like Mr. Reale should make even these rough
sketches unless he had a model to draw from?”
“Miss Kent is right,” said Jimmy quickly.
“And,” she went on, gaining confidence as she spoke, “is there not
something about these drawings that reminds you of something?”
“Of what?” asked Angel.
“I cannot tell,” she replied, shaking her head; “and yet they remind
me of something, and worry me, just as a bar of music that I cannot
play worries me. I feel sure that I have seen them before, that they
form a part of some system——” She stopped suddenly.
“I know,” she continued in a lower voice; “they are associated in my
mind—with—with the Bible.”
The two men stared at her in blank astonishment. Then Jimmy
sprang to his feet, alight with excitement.
“Yes, yes,” he cried. “Angel, don’t you see? The last two lines of
Reale’s doggerel—
“‘I found this puzzle in a book
From which some mighty truths were took.’”
“Go on, go on, Miss Kent,” cried Angel eagerly. “You are on the right
track. Try to think——”
Kathleen hesitated, then turned to Jimmy to address the first remark
she had directed to him personally that day.
“You haven’t got——?”
Jimmy’s smile was a little hard.
“I’m sorry to disappoint you, Miss Kent, but I have got a copy,” he
said, with a touch of bitterness in his tone. He walked to the
bookcase at one end of the room and reached down the book—a
well-worn volume—and placed it before her.
The rebuke in his voice was deserved, she felt that.
She turned the leaves over quickly, but inspiration seemed to have
died, for there was nothing in the sacred volume that marshaled her
struggling thoughts.
“Is it a text?” asked Angel.
She shook her head.
“It is—something,” she said. “That sounds vague, doesn’t it? I
thought if I had the book in my hand, it would recall everything.”
Angel was intently studying the rebus.
“Here’s one letter, anyway. You said that, Jimmy?”
“The door?” said Jimmy. “Yes, that’s fairly evident. Whatever the
word is, its second letter is ‘P.’ You see Reale’s scribbled notes? All
these are no good, the other letters are best, I suppose it means; so
we can cut out ‘T,’ ‘O,’ and ‘K.’”
“The best clue of all,” he went on, “is the notes about the ‘professor.’
You see them:
“‘Mem.: To get the professor’s new book on it.
Mem.: To do what the professor thinks right.
Mem.: To write to professor about——’
Now the questions are: Who is the professor, what is his book, and
what did he advise? Reale was in correspondence with him, that is
certain; in his desire for accuracy, Reale sought his advice. In all
these papers there is no trace of a letter, and if any book exists it is
still in Sped—it is still in the place from whence this red envelope
came.”
The two men exchanged a swift glance.
“Yes,” said Angel, as if answering the other’s unspoken thought, “it
might be done.”
The girl looked from one to the other in doubt.
“Does this mean an extra risk?” she asked quietly. “I have not
questioned you as to how this red envelope came into your
possession, but I have a feeling that it was not obtained without
danger.”
Angel disregarded Jimmy’s warning frown. He was determined that
the better side of his strange friend’s character should be made
evident to the girl.
“Jimmy faced death in a particularly unpleasant form to secure the
packet, Miss Kent,” he said.
“Then I forbid any further risk,” she said spiritedly. “I thought I had
made it clear that I would not accept favors at your friend’s hands;
least of all do I want the favor of his life.”
Jimmy heard her unmoved. He had a bitter tongue when he so
willed, and he chose that moment.
“I do not think you can too strongly impress upon Miss Kent the fact
that I am an interested party in this matter,” he said acidly. “As she
refused my offer to forego my claim to a share of the fortune, she
might remember that my interest in the legacy is at least as great as
hers. I am risking what I risk, not so much from the beautifully
quixotic motives with which she doubtless credits me, as from a
natural desire to help myself.”
She winced a little at the bluntness of his speech; then recognizing
she was in the wrong, she grew angry with herself at her
indiscretion.
“If the book is—where these papers were, it can be secured,” Jimmy
continued, regaining his suavity. “If the professor is still alive he will
be found, and by to-morrow I shall have in my possession a list of
every book that has ever been written by a professor of anything.”
Some thought tickled him, and he laughed for the second time that
afternoon.
“There’s a fine course of reading for us all,” he said with a little
chuckle. “Heaven knows into what mysterious regions the literary
professor will lead us. I know one professor who has written a
treatise on Sociology that runs into ten volumes, and another who
has spoken his mind on Inductive Logic to the extent of twelve
hundred closely-printed pages. I have in my mind’s eye a vision of
three people sitting amidst a chaos of thoughtful literature, searching
ponderous tomes for esoteric references to bolts, door, mouth, et
cetera.”
The picture he drew was too much for the gravity of the girl, and her
friendship with the man who was professedly a thief, and by
inference something worse, began with a ripple of laughter that
greeted his sally.
Jimmy gathered up the papers, and carefully replaced them in the
envelope. This he handed to Angel.
“Place this amongst the archives,” he said flippantly.
“Why not keep it here?” asked Angel in surprise.
Jimmy walked to one of the three French windows that opened on to
a small balcony. He took a rapid survey of the street, then beckoned
to Angel.
“Do you see that man?” He pointed to a lounger sauntering along on
the opposite sidewalk.
“Yes.”
Jimmy walked back to the center of the room.
“That’s why,” he said simply. “There will be a burglary here to-night or
to-morrow night. People aren’t going to let a fortune slip through their
fingers without making some kind of effort to save it.”
“What people?” demanded the girl. “You mean those dreadful men
who took me away?”
“That is very possible,” said Jimmy, “although I was thinking of
somebody else.”
The girl had put on her wrap, and stood irresolutely near the door,
and Angel was waiting.
“Good-by,” she said hesitatingly. “I—I am afraid I have done you an
injustice, and—and I want to thank you for all you have undergone
for me. I know—I feel that I have been ungracious, and——”
“You have done me no injustice,” said Jimmy in a low voice. “I am all
that you thought I was—and worse.”
She held out her hand to him, and he raised it to his lips, which was
unlike Jimmy.
CHAPTER VIII
OLD GEORGE

A stranger making a call in that portion of North Kensington which


lies in the vicinity of Ladbroke Grove by some mischance lost his
way. He wandered through many prosperous crescents and quiet
squares redolent of the opulence of the upper middle classes,
through broad avenues where neat broughams stood waiting in
small carriage-drives, and once he blundered into a tidy mews,
where horsy men with great hissings made ready the chariots of the
Notting Hill plutocracy. It may be that he was in no particular hurry to
arrive at his destination, this stranger—who has nothing to do with
the story—but certainly he did not avail himself of opportunity in the
shape of a passing policeman, and continued his aimless
wanderings. He found Kensington Park Road, a broad thoroughfare
of huge gardens and walled forecourts, then turned into a side street.
He walked about twenty paces, and found himself in the heart of
slum-land.
It is no ordinary slum this little patch of property that lies between
Westbourne Grove and Kensington Park Road. There are no
tumbled-down hovels or noisome passages; there are streets of
houses dignified with flights of steps that rise to pretentious street
doors and areas where long dead menials served the need of the
lower middle classes of other days. The streets are given over to an
army of squalling children in varying styles of dirtiness, and the halls
of these houses are bare of carpet or covering, and in some the
responsibility of leasehold is shared by eight or nine families, all
pigging together.
They are streets of slatternly women, who live at their front doors,
arms rolled under discolored aprons, and on Saturday nights one
street at least deserves the pithy but profane appellation which the
police have given it—“Little Hell.”
In this particular thoroughfare it is held that of all sins the greatest is
that which is associated with “spying.” A “spy” is a fairly
comprehensive phrase in Cawdor Street. It may mean policeman,
detective, school-board official, rent collector, or the gentleman
appointed by the gas company to extract pennies from the slot-
meters.
To Cawdor Street came a man who rented one of the larger houses.
To the surprise of the agent, he offered his rent monthly in advance;
to the surprise of the street, he took no lodgers. It was the only
detached house in that salubrious road, and was No. 49. The
furniture came by night, which is customary amongst people who
concentrate their last fluttering rag of pride upon the respectability of
their household goods. Cawdor Street, on the qui vive for the lady of
the house, learns with genuine astonishment that there was none,
and that the newcomer was a bachelor.
Years ago No. 49 had been the abode of a jobbing builder, hence the
little yard gate that flanked one side; and it was with satisfaction that
the Cawdor Streeters discovered that the new occupant intended
reviving the ancient splendor of the establishment. At any rate, a
board was prominently displayed, bearing the inscription:
J. JONES, BUILDER AND CONTRACTOR.
and the inquisitive Mr. Lane (of 76), who caught a momentary vision
of the yard through the gate, observed “Office” printed in fairly large
letters over the side door.
At stated hours, mostly in the evening, roughly-dressed men called
at the “Office,” stayed awhile, and went away. Two dilapidated
ladders made their appearance in the yard, conspicuously lifting their
perished rungs above the gate level.
“I tried to buy an old builder’s cart and a wheelbarrow to-day,” said
“Mr. Jones” to a workman. “I’ll probably get it to-morrow at my own
price, and it wouldn’t be a bad idea to get a few sacks of lime and a
couple of cartloads of sand and bricks in, also a few road pitchers to
give it a finishing touch.”
The workman grinned.
“You’ve got this place ready in time, Connor,” he said.
Mr. Connor—for such “J. Jones, Builder and Contractor” was—
nodded and picked his teeth meditatively with a match stick.
“I’ve seen for a long time the other place was useless,” he said with
a curse.
“It was bad luck that Angel found us there last week. I’ve been fixing
up this house for a couple of months. It’s a nice neighborhood,
where people don’t go nosing around, and the boys can meet here
without anybody being the wiser.”
“And old George?”
“We’ll settle him to-night,” said the other with a frown. “Bat is bringing
him over, and I want to know how he came to let Angel get at us.”
Old George had always been a problem to the “Borough Lot.” He
held the position of trust that many contended no demented old man
should hold. Was it safe or sane to trust him with the plate that had
been so laboriously acquired from Roebury House, and the jewels of
Lady Ivy Task-Hender, for the purloining of which one “Hog” Stander
was at that very moment doing seven stretch? Was it wise to install
him as custodian of the empty house at Blackwall, through which
Angel Esquire gained admittance to the meeting-place of the
“Borough Lot”?
Some there were who said “Yes,” and these included the powerful
faction that numbered “Bat” Sands, “Curt” Goyle, and Connor
amongst them. They contended that suspicion would never rest on
this half-witted old gentleman, with his stuffed birds, his goldfish,
caged rabbits and mice, a view that was supported by the fact that
Lady Ivy’s priceless diamonds lay concealed for months in the false
bottom of a hutch devoted to guinea pigs in old George’s strange
menagerie, what time the police were turning London inside out in
their quest for the property.
But now old George was under a cloud. Notwithstanding the fact that
he had been found amongst his live stock securely bound to a chair,
with a handkerchief over his mouth, suspicion attached to him. How
had Angel worked away in the upper room without old George’s
knowledge?
Angel might have easily explained. Indeed, Angel might have
relieved their minds to a very large extent in regard to old George,
for in marking down the haunt of the “Borough Lot” he had been
entirely deceived as to the part played by the old man who acted as
“caretaker” to the “empty” house.
In a fourwheeled cab old George, smiling foolishly and passing his
hand from time to time over his tremulous mouth, listened to the
admonitions of Mr. Bat Sands.
“Connor wants to know all about it,” said Bat menacingly; “and if you
have been playing tricks, old man, the Lord help you.”
“The Lord help me,” smiled old George complacently.
He ran his dirty fingers through his few scanty white locks, and the
smile died out of his face, and his loose mouth dropped pathetically.
“Mr. Sands,” he said, then stopped; then he repeated the name to
himself a dozen times; then he rubbed his head again.
Bat, leaning forward to catch what might be a confession, sank back
again in his seat and swore softly.
In the house of “J. Jones, Builder and Contractor,” were gathered in
strength the men who composed the “Borough Lot.”
“Suppose he gave us away,” asked Goyle, “what shall we do with
him?”
There was little doubt as to the feeling of the meeting. A low animal
growl, startling in its ferocity, ran through the gathering.
“If he’s given us away”—it was Vinnis with his dull fishlike eyes
turned upon Connor who was talking—“why, we must ‘out’ him.”
“You’re talking like a fool,” said Connor contemptuously. “If he has
given us away, you may rest assured that he is no sooner in this
house than the whole place will be surrounded by police. If Angel
knows old George is one of us, he’ll be watched day and night, and
the cab that brings him will be followed by another bringing Angel.
No, I’ll stake my life on the old man. But I want to know how Mr.
Cursed Angel got into the house next door.”
They had not long to wait, for Bat’s knock came almost as Connor
finished speaking.
Half led, half dragged into the room, old George stood, fumbling his
hat in his hand, smiling helplessly at the dark faces that met his. He
muttered something under his breath.
“What’s that?” asked Connor sharply.
“I said, a gentleman——” began old George, then lapsed into
silence.
“What gentleman?” asked Connor roughly.
“I am speaking of myself,” said the old man, and there came into his
face a curious expression of dignity. “I say, and I maintain, that a
gentleman is a gentleman whatever company he affects. At my old
college I once reproved an undergraduate.” He was speaking with
stately, almost pompous distinctness. “I said, ‘There is an axiom to
which I would refer you, De gustibus non est disputandum, and—and
——’”
His shaking fingers went up again to the tell-tale mouth, and the
vacant smile came back.
“Look here,” said Connor, shaking his arm, “we don’t want to know
anything about your damned college; we want to know how Angel
got into our crib.”
The old man looked puzzled.
“Yes, yes,” he muttered; “of course, Mr. Connor, you have been most
kind—the crib—ah!—the young man who wanted to rent or hire the
room upstairs.”
“Yes, yes,” said Connor eagerly.
“A most admirable young man,” old George rambled on, “but very
inquisitive. I remember once, when I was addressing a large
congregation of young men at Cheltenham—or it may have been
young ladies—I——”
“Curse the man!” cried Goyle in a fury. “Make him answer, or stop his
mouth.”
Connor warned him back.
“Let him talk in his own way,” he said.
“This admirable person,” the old man went on, happily striking on the
subject again, “desired information that I was not disposed to give,
Mr. Connor, remembering your many kindnesses, particularly in
respect to one Mr. Vinnis.”
“Yes, go on,” urged Connor, and the face of Vinnis was tense.
“I fear there are times when my usually active mind takes on a
sluggishness which is foreign to my character—my normal
character”—old George was again the pedant—“when the
unobservant stranger might be deceived into regarding me as a
negligible quantity. The admirable young man so far treated me as
such as to remark to his companion that there was a rope—yes,
distinctly a rope—for the said Mr. Vinnis.”
The face of Vinnis was livid.
“And,” asked Connor, “what happened next? There were two of
them, were there?”
The old man nodded gravely; he nodded a number of times, as
though the exercise pleased him.
“The other young man—not the amiable one, but another—upon
finding that I could not rent or hire the rooms—as indeed I could not,
Mr. Connor, without your permission—engaged me in conversation—
very loudly he spoke, too—on the relative values of cabbage and
carrot as food for herbaceous mammals. Where the amiable
gentleman was at that moment I cannot say——”
“I can guess,” thought Connor.
“I can remember the occasion well,” old George continued, “because
that night I was alarmed and startled by strange noises from the
empty rooms upstairs, which I very naturally and properly concluded
were caused——”
He stopped, and glancing fearfully about the room, went on in a
lower tone.
“By certain spirits,” he whispered mysteriously, and pointed and
leered first at one and then another of the occupants of the room.
There was something very eerie in the performance of the strange
old man with the queerly-working face, and more than one hardened
criminal present shivered a little.
Connor broke the silence that fell on the room.
“So that’s how it was done, eh? One held you in conversation while
the other got upstairs and hid himself? Well, boys, you’ve heard the
old man. What d’ye say?”
Vinnis shifted in his seat and turned his great unemotional face to
where the old man stood, still fumbling with his hat and muttering to
himself beneath his breath; in some strange region whither his poor
wandering mind had taken him he was holding a conversation with
an imaginary person. Connor could see his eyebrows working, and
caught scraps of sentences, now in some strange dead tongue, now
in the stilted English of the schoolmaster.
It was Vinnis who spoke for the assembled company.
“The old man knows a darned sight too much,” he said in his level
tone. “I’m for——”
He did not finish his sentence. Connor took a swift survey of the
men.
“If there is any man here,” he said slowly, “who wants to wake up at
seven o’clock in the morning and meet a gentleman who will strap
his hands behind him and a person who will pray over him—if there’s
any man here that wants a short walk after breakfast between two
lines of warders to a little shed where a brand new rope is hanging
from the roof, he’s at liberty to do what he likes with old George, but
not in this house.”
He fixed his eyes on Vinnis.
“And if there’s any man here,” he went on, “who’s already in the
shadow of the rope, so that one or two murders more won’t make
much difference one way or the other, he can do as he likes—
outside this house.”
Vinnis shrank back.
“There’s nothing against me,” he growled.
“The rope,” muttered the old man, “Vinnis for the rope,” he chuckled
to himself. “I fear they counted too implicitly upon the fact that I am
not always quite myself—Vinnis——”
The man he spoke of sprang to his feet with a snarl like a trapped
beast.
“Sit down—you.”
Bat Sands, with his red head close-cropped, thrust his chair in the
direction of the infuriated Vinnis.
“What Connor says is true—we’re not going to croak the old man,
and we’re not going to croak ourselves. If we hang, it will be
something worth hanging for. As to the old man, he’s soft, an’ that’s
all you can say. He’s got to be kept close——”
A rap at the door cut him short.
“Who’s that?” he whispered.
Connor tiptoed to the locked door.
“Who’s there?” he demanded.
A familiar voice reassured him, and he opened the door and held a
conversation in a low voice with somebody outside.
“There’s a man who wants to see me,” he said in explanation. “Lock
the door after I leave, Bat,” and he went out quickly.
Not a word was spoken, but each after his own fashion of reasoning
drew some conclusion from Connor’s hasty departure.
“A full meetin’,” croaked a voice from the back of the room. “We’re all
asked here by Connor. Is it a plant?”
That was Bat’s thought too.
“No,” he said; “there’s nothin’ against us. Why, Angel let us off only
last week because there wasn’t evidence, an’ Connor’s straight.”
“I don’t trust him, by God!” said Vinnis.
“I trust nobody,” said Bat doggedly, “but Connor’s straight——”
There was a rap on the door.
“Who’s there?”
“All right!” said the muffled voice.
Bat unlocked the door, and Connor came in. What he had seen or
what he had heard had brought about a marvelous change in his
appearance—his cheeks were a dull red, and his eyes blazed with
triumph.
“Boys,” he said, and they caught the infectious thrill in his voice, “I’ve
got the biggest thing for you—a million pounds, share and share
alike.”
He felt rather than heard the excitement his words caused. He stood
with his back to the half-opened door.
“I’m going to introduce a new pal,” he rattled on breathlessly. “I’ll
vouch for him.”
“Who is he?” asked Bat. “Do we know him?”
“No,” said Connor, “and you’re not expected to know him. But he’s
putting up the money, and that’s good enough for you, Bat—a
hundred pounds a man, and it will be paid to-night.”
Bat Sands spat on his hand.
“Bring him in. He’s good enough,” and there was a murmur of
approval.
Connor disappeared for a moment, and returned followed by a well-
dressed stranger, who met the questioning glances of his audience
with a quiet smile. His eyes swept over every face. They rested for a
moment on Vinnis, they looked doubtfully at old George, who, seated

You might also like