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

Download ebooks file Java Programming Exercises Volume Two Java Standard Library 1st Edition Christian Ullenboom all chapters

The document provides information about the book 'Java Programming Exercises Volume Two: Java Standard Library' by Christian Ullenboom, which includes 149 programming tasks with solutions to enhance coding skills in Java. It covers various programming paradigms and emphasizes clean code and thoughtful design. Additionally, it offers links to download the book and other related Java programming ebooks.

Uploaded by

lingavolpefd
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)
264 views

Download ebooks file Java Programming Exercises Volume Two Java Standard Library 1st Edition Christian Ullenboom all chapters

The document provides information about the book 'Java Programming Exercises Volume Two: Java Standard Library' by Christian Ullenboom, which includes 149 programming tasks with solutions to enhance coding skills in Java. It covers various programming paradigms and emphasizes clean code and thoughtful design. Additionally, it offers links to download the book and other related Java programming ebooks.

Uploaded by

lingavolpefd
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/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Java Programming Exercises Volume Two Java


Standard Library 1st Edition Christian Ullenboom

_____ Click the link below to download _____


https://ebookfinal.com/download/java-programming-
exercises-volume-two-java-standard-library-1st-edition-
christian-ullenboom/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Simply Java An Introduction to Java Programming


Programming Series 1st Edition James Levenick

https://ebookfinal.com/download/simply-java-an-introduction-to-java-
programming-programming-series-1st-edition-james-levenick/

Learn Java Fundamentals A Primer for Java Development and


Programming 1st Edition Jeff Friesen

https://ebookfinal.com/download/learn-java-fundamentals-a-primer-for-
java-development-and-programming-1st-edition-jeff-friesen/

Java Servlet Programming Second Edition Jason Hunter

https://ebookfinal.com/download/java-servlet-programming-second-
edition-jason-hunter/

Wireless Java Programming with J2ME 1st Edition Yu Feng

https://ebookfinal.com/download/wireless-java-programming-
with-j2me-1st-edition-yu-feng/
Java Programming 24 Hour Trainer 1st Edition Yakov Fain

https://ebookfinal.com/download/java-programming-24-hour-trainer-1st-
edition-yakov-fain/

Object Oriented Programming using Java 1st edition Edition


Kendal S.

https://ebookfinal.com/download/object-oriented-programming-using-
java-1st-edition-edition-kendal-s/

Object Oriented Programming and Java Second Edition Danny


Poo

https://ebookfinal.com/download/object-oriented-programming-and-java-
second-edition-danny-poo/

Introduction to Java Programming Comprehensive Version 6th


Edition Liang

https://ebookfinal.com/download/introduction-to-java-programming-
comprehensive-version-6th-edition-liang/

Elements of Programming Interviews in Java 2nd Edition


Adnan Aziz

https://ebookfinal.com/download/elements-of-programming-interviews-in-
java-2nd-edition-adnan-aziz/
Java Programming Exercises Volume Two Java Standard
Library 1st Edition Christian Ullenboom Digital Instant
Download
Author(s): Christian Ullenboom
ISBN(s): 9781032798011, 1032798017
Edition: 1
File Details: PDF, 7.86 MB
Year: 2024
Language: english
Java Programming Exercises
Take the next step in raising your coding skills and dive into the intricacies of Java Standard Libraries.
You will continue to raise your coding skills, and test your Java knowledge on tricky programming tasks,
with the help of the pirate Captain CiaoCiao. This is the second 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:

• 149 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 Two: Java Standard Library

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 mpkbookspermissions@tandf.co.uk

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‑80117‑9 (hbk)


ISBN: 978‑1‑032‑79801‑1 (pbk)
ISBN: 978‑1‑003‑49555‑0 (ebk)

DOI: 10.1201/9781003495550

Typeset in Times
by codeMantra

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


Contents

About the Author xiii

Introduction 1
Previous Knowledge and Target Audience 1
Working with the Book 2
The Suggested Solutions 2
Use of the 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 Advanced String Processing 6


Format Strings 6
Build ASCII Table ⭑ 6
Aligned Outputs ⭑ 8
Regular Expressions and Pattern Recognition 8
Quiz: Define Regex ⭑ 8
Determine Popularity in Social Media ⭑ 8
Detect Scanned Values ⭑ 9
Quiet Please! Defuse Shouting Texts ⭑ 10
Converting Time from AM/PM Format to 24‑Hour Format ⭑⭑ 11
Decompose Strings into Tokens 12
Split Address Lines with the StringTokenizer ⭑ 12
Split Sentences into Words and Reverse Them ⭑ 13
Check Relations between Numbers ⭑ 13
Convert A1 Notation to Columns and Rows ⭑⭑ 13
Parse Simple CSV Files with Coordinates ⭑ 14
Compress Strings Lossless by Runlength Encoding ⭑⭑⭑ 14
Character Encodings and Unicode Collation Algorithm 15
Quiz: Encoding for Unicode Characters ⭑ 15
Quiz: Order of Strings with and without Collator ⭑ 16
Suggested Solutions 16
Build ASCII Table 16
Aligned Outputs 17
Quiz: Define Regex 18
Determine Popularity in Social Media 19
Detect Scanned Values 19
Quiet Please! Defuse Shouting Texts 20
Converting Time from AM/PM Format to 24‑Hour Format 20
Split Address Lines with the StringTokenizer 21

v
vi Contents

Split Sentences into Words and Reverse Them 22


Check Relations between Numbers 23
Convert A1 Notation to Columns and Rows 24
Parse Simple CSV Files with Coordinates 25
Compress Strings Lossless by Runlength Encoding 26
Quiz: Encoding for Unicode Characters 28
Quiz: Order of Strings with and without Collator 28

2 Mathematics 30
The Class Math 30
Quiz: Rule of Thumb ⭑ 30
Check If Tin Tin Cheated on Rounding ⭑ 31
Huge and Very Precise Numbers 32
Calculate Arithmetic Mean of a Large Integer ⭑ 32
Number by Number over the Phone ⭑ 33
Develop Class for Fractions and Truncate Fractions ⭑⭑ 34
Suggested Solutions 35
Quiz: Rule of Thumb 35
Check If Tin Tin Cheated on Rounding 36
Calculate Arithmetic Mean of a Large Integer 37
Number by Number over the Phone 38
Develop Class for Fractions and Truncate Fractions 38

3 Locale, Date, and Time 42


Languages and Countries 42
Apply Country‑/Language‑Specific Formatting for Random Number ⭑ 43
Date and Time Classes 44
Formatting Date Output in Different Languages ⭑ 44
On Which Day Does Sir Francis Beaufort Celebrate His Birthday? ⭑ 45
Find All Friday the 13th ⭑ 45
Get Average Duration of Karaoke Nights ⭑ 46
Parse Different Date Formats ⭑⭑⭑ 46
Suggested Solutions 47
Apply Country‑/Language‑Specific Formatting for Random Number 47
Formatting Date Output in Different Languages 47
On Which Day Does Sir Francis Beaufort Celebrate His Birthday? 48
Find All Friday the 13th 50
Get Average Duration of Karaoke Nights 51
Parse Different Date Formats 52

4 Concurrent Programming with Threads 54


Create Threads 55
Create Threads for Waving and Flag Waving ⭑ 56
No More Waving Flags: End Threads ⭑ 56
Parameterize Runnable ⭑⭑ 56
Execute and Idle 57
Delay Execution by Sleeping Threads ⭑⭑ 57
Watch File Changes by Threads ⭑ 58
Catch Exceptions ⭑ 58
Thread Pools and Results 59
Using Thread Pools ⭑⭑ 60
Get Last Modification of Web Pages ⭑⭑ 60
Contents vii

Protect Critical Sections 61


Writing Memories into a Poetry Album ⭑ 62
Thread Cooperation and Synchronization Helper 64
Attending the Banquet with the Captains—Semaphore ⭑⭑ 64
Swearing and Insulting—Condition ⭑⭑ 65
Take Pens Out of Paintbox—Condition ⭑⭑ 65
Play Rock, Paper, Scissors—CyclicBarrier ⭑⭑⭑ 66
Find the Fastest Runner—CountDownLatch ⭑⭑ 67
Suggested Solutions 68
Create Threads for Waving and Flag Waving 68
No More Waving Flags: End Threads 69
Parameterize Runnable 70
Delay Execution by Sleeping Threads 70
Watch File Changes by Threads 72
Catch Exceptions 73
Using Thread Pools 74
Get Last Modification of Web Pages 75
Writing Memories into a Poetry Album 77
Attending the Banquet with the Captains—Semaphore 78
Swearing and Insulting—Condition 79
Take Pens Out of Paintbox—Condition 80
Play Rock, Paper, Scissors—CyclicBarrier 82
Find the Fastest Runner—CountDownLatch 83

5 Data Structures and Algorithms 85


The Types of the Collection API 86
Quiz: Search for StringBuilder ⭑ 87
Lists 88
Singing and Cooking: Traverse Lists and Check Properties ⭑ 88
Filter Comments from Lists ⭑ 89
Shorten Lists Because There Is No Downturn ⭑ 89
Eating with Friends: Compare Elements, Find Commonalities ⭑ 90
Check Lists for the Same Order of Elements ⭑ 90
And Now the Weather: Find Repeated Elements ⭑ 91
Generate Receipt Output ⭑ 92
Quiz: Arrays Decorated ⭑ 92
Quiz: Searched and Not Found ⭑ 92
Everything Tastes Better with Cheese: Insert Elements into Lists ⭑ 93
Quiz: With Nothing but Trouble ⭑ 93
Search Elements with the Iterator and Find Covid Cough ⭑⭑ 94
Move Elements, Play Musical Chairs ⭑ 95
Programming a Question Game with Planets ⭑⭑ 95
Sets 97
Form Subsets, Find Common Elements ⭑ 97
Quiz: Great Swords ⭑ 98
Get All Words Contained in a Word ⭑⭑ 99
Exclude Duplicate Elements with a UniqueIterator ⭑⭑ 99
Map Keys to Values 100
Convert Two‑Dimensional Arrays to Map ⭑ 100
Convert Text to Morse Code and Vice Versa ⭑ 101
Remember Word Frequency with Associative Memory ⭑⭑ 101
Read In and Read Out Colors ⭑⭑ 102
viii Contents

Read in Names and Manage Lengths ⭑ 103


Find Missing Characters ⭑⭑ 103
Calculate Number of Paths to the Three‑Headed Monkey ⭑⭑ 103
Manage Holidays in a Sorted Associative Store ⭑ 104
Quiz: Keys in a HashMap ⭑⭑ 105
Determine Commonality: Party Set and Souvenir ⭑ 106
Properties 106
Develop Convenient Properties Decorator ⭑⭑ 106
Stack and Queues 108
Program RPN Pocket Calculator ⭑ 108
BitSet 109
Forget No Ship ⭑ 109
Find Duplicate Entries and Solve the Animal Chaos ⭑ 110
Thread‑Safe Data Structures 110
Loading Ship ⭑⭑ 111
Handle Important Messages First ⭑⭑ 112
If Used Up, Create a New One ⭑⭑⭑ 113
Suggested Solutions 114
Quiz: Search for StringBuilder 114
Singing and Cooking: Traverse Lists and Check Properties 114
Filter Comments from Lists 116
Shorten Lists Because There Is No Downturn 117
Eating with Friends: Compare Elements, Find Commonalities 118
Check Lists for the Same Order of Elements 118
And Now the Weather: Find Repeated Elements 120
Generate Receipt Output 121
Quiz: Arrays Decorated 123
Quiz: Searched and Not Found 124
Everything Tastes Better with Cheese: Insert Elements into Lists 124
Quiz: With Nothing but Trouble 125
Search Elements with the Iterator and Find Covid Cough 126
Move Elements, Play Musical Chairs 128
Programming a Question Game with Planets 129
Form Subsets, Find Common Elements 130
Quiz: Great Swords 131
Get All Words Contained in a Word 132
Exclude Duplicate Elements with a UniqueIterator 133
Convert Two-Dimensional Arrays to Map 134
Convert Text to Morse Code and Vice Versa 136
Remember Word Frequency with Associative Memory 138
Read In and Read Out Colors 140
Read in Names and Manage Lengths 141
Find Missing Characters 143
Calculate the Number of Paths to the Three-Headed Monkey 145
Manage Holidays in a Sorted Associative Store 146
Quiz: Keys in a HashMap 147
Determine Commonality: Party Set and Souvenir 148
Develop Convenient Properties Decorator 148
Program RPN Pocket Calculator 150
Forget No Ship 151
Find Duplicate Entries and Solve the Animal Chaos 152
Loading Ship 153
Contents ix

Handle Important Messages First 154


If Used Up, Create a New One 155
Notes 156

6 Java Stream-API 157


Regular Streams with Their Terminal and Intermediate Operations 157
Hero Epic: Meet Stream API ⭑ 157
Quiz: Double Output ⭑ 158
Get the Beloved Captain from a List ⭑ 158
Frame Pictures ⭑ 159
Look and Say ⭑⭑ 160
Remove Duplicate Islands of Rare Earth Metals ⭑⭑⭑ 161
Where Are the Sails? ⭑⭑ 162
Buy the Most Popular Car ⭑⭑⭑ 163
Primitive Streams 163
Detect NaN in an Array ⭑ 163
Generate Decades ⭑ 164
Generate Array with Constant Content via Stream ⭑ 164
Draw Pyramids ⭑ 165
Teddies Labeled with Letters ⭑ 165
Get the Letter Frequency of a String ⭑ 166
From 1 to 0, from 10 to 9 ⭑⭑ 166
The Annual Octopus Contest ⭑⭑ 166
Merge Three int Arrays ⭑ 167
Determine Winning Combinations ⭑⭑ 167
Statistics 168
The Fastest and Slowest Paddlers ⭑ 168
Calculate Median ⭑⭑ 169
Calculate Temperature Statistics and Draw Charts ⭑⭑⭑ 169
Suggested Solutions 170
Hero Epic: Meet Stream API 170
Quiz: Double Output 176
Get the Beloved Captain from a List 176
Frame Pictures 177
Look and Say 178
Remove Duplicate Islands of Rare Earth Metals 179
Where Are the Sails? 181
Buy the Most Popular Car 182
Detect NaN in an Array 183
Generate Decades 183
Generate Array with Constant Content via Stream 184
Teddies Labeled with Letters 184
Draw Pyramids 185
Get the Letter Frequency of a String 185
From 1 to 0, from 10 to 9 186
The Annual Octopus Contest 187
Merge Three int Arrays 188
Determine Winning Combinations 189
The Fastest and Slowest Paddlers 189
Calculate Median 190
Calculate Temperature Statistics and Draw Charts 191
Note 195
x Contents

7 Files, Directories, and File Access 196


Path and Files 196
Display Saying of the Day ⭑ 197
Merge Hiding Places ⭑ 197
Create Copies of a File ⭑⭑ 197
Generate a Directory Listing ⭑ 198
Search for Large GIF Files ⭑ 198
Descend Directories Recursively and Find Empty Text Files ⭑ 198
Develop Your Own Utility Library for File Filters ⭑⭑⭑ 199
Random Access to File Contents 199
Output Last Line of a Text File ⭑⭑ 200
Suggested Solutions 200
Display Saying of the Day 200
Merge Hiding Places 201
Create Copies of a File 201
Generate a Directory Listing 202
Search for Large GIF Files 203
Descend Directories Recursively and Find Empty Text Files 204
Develop Your Own Utility Library for File Filters 205
Output Last Line of a Text File 208

8 Input/Output Streams 210


Direct Data Streams 211
Get the Number of Different Places (Read Files) ⭑ 211
Convert Python Program to Java (Write File) ⭑ 211
Generate Target Code (Write File) ⭑ 212
Convert File Contents to Lowercase (Read and Write File) ⭑ 213
Convert PPM Graphics to ASCII Grayscale ⭑⭑⭑ 213
Split Files (Read and Write Files) ⭑⭑ 215
Nesting Streams 215
Quiz: DataInputStream and DataOutputStream ⭑ 215
Compress Number Sequences with the GZIPOutputStream ⭑ 216
Serialization 216
(De)serialize Data for Chat and Convert It to Text ⭑⭑ 216
Quiz: Requirement for Serialization ⭑ 217
Save Last Inputs ⭑⭑ 217
Suggested Solutions 218
Get the Number of Different Places (Read Files) 218
Convert Python Program to Java (Write File) 219
Generate Target Code (Write File) 220
Convert File Contents to Lowercase (Read and Write File) 221
Convert PPM Graphics to ASCII Gray Scale 222
Split Files (Read and Write Files) 224
Quiz: DataInputStream and DataOutputStream 225
Compress Number Sequences with the GZIPOutputStream 228
(De)serialize Data for Chat and Convert Them to Text 229
Quiz: Requirement for Serialization 230
Save Last Inputs 231
Note 233
Contents xi

9 Network Programming 234


URL and URLConnection 234
Download Remote Images via URL ⭑ 235
Read Remote Text File from URL ⭑ 235
HTTP Client 236
Top News from Hacker News ⭑⭑ 236
Socket and ServerSocket 237
Implement a Swear Server and a Client ⭑⭑ 237
Implement a Port Scanner ⭑⭑ 237
Suggested Solutions 238
Download Remote Images via URL 238
Read Remote Text File from URL 239
Top News from Hacker News 240
Implement a Swear Server and a Client 241
Implement a Port Scanner 243

10 Process XML, JSON, and Other Data Formats 246


XML Processing with Java 247
Write XML File with Recipe ⭑ 247
Check If All Images Have an alt Attribute ⭑ 248
Writing Java Objects with JAXB ⭑ 248
Read in Jokes and Laugh Heartily ⭑⭑ 249
JSON 251
Hacker News JSON Exploit ⭑ 251
Read and Write Editor Configurations as JSON ⭑⭑ 252
HTML 253
Load Wikipedia Images with jsoup ⭑⭑ 253
Office Documents 253
Generate Word Files with Screenshots ⭑⭑ 253
Archives 254
Play Insect Sounds from ZIP Archive ⭑⭑ 254
Suggested Solutions 255
Write XML File with Recipe 255
Check If All Images Have an alt Attribute 258
Writing Java Objects with JAXB 259
Read in Jokes and Laugh Heartily 260
Hacker News JSON Exploit 261
Read and Write Editor Configurations as JSON 262
Load Wikipedia Images with jsoup 263
Generate Word Files with Screenshots 264
Play Insect Sounds from ZIP Archive 265
Note 266

11 Database Access with JDBC 267


Database Management Systems 267
Prepare H2 Database ⭑ 268
Database Queries 268
Query All Registered JDBC Drivers ⭑ 268
Build Database and Execute SQL Script ⭑ 269
Insert Data into the Database ⭑ 270
Insert Data into the Database in Batch Mode ⭑ 271
xii Contents

Insert Data with Prepared Statements ⭑ 271


Request Data ⭑ 272
Interactive Scrolling through the ResultSet ⭑ 272
Pirate Repository ⭑⭑ 272
Query Column Metadata ⭑ 273
Suggested Solutions 274
Query All Registered JDBC Drivers 274
Build Database and Execute SQL Script 274
Insert Data into the Database 275
Insert Data into the Database in Batch Mode 276
Insert Data with Prepared Statements 277
Request Data 277
Interactive Scrolling through the ResultSet 278
Pirate Repository 279
Query Column Metadata 282

12 Operating System Access 284


Console 284
Colored Console Outputs ⭑ 285
Properties 286
Windows, Unix, or macOS? ⭑ 286
Unify Command‑Line Properties and Properties from Files ⭑ 286
Execute External Processes 287
Read the Battery Status via Windows Management Instrumentation ⭑⭑ 287
Suggested Solutions 288
Colored Console Outputs 288
Windows, Unix, or macOS? 288
Unify Command‑Line Properties and Properties from Files 289
Read the Battery Status via Windows Management Instrumentation 290

13 Reflection, Annotations, and JavaBeans 294


Reflection API 294
Create UML Class Diagram with Inheritance Relationships ⭑ 295
Create UML Class Diagram with Properties ⭑ 296
Generate CSV Files from List Entries ⭑⭑ 297
Annotations 297
Create CSV Documents from Annotated Instance Variables ⭑⭑ 297
Suggested Solutions 298
Create UML Class Diagram with Inheritance Relationships 298
Create UML Class Diagram with Properties 299
Generate CSV Files from List Entries 301
Create CSV Documents from Annotated Instance Variables 301

Epilogue 307
Code Golf Stack Exchange 307
Project Euler 307
Daily Programmer 307
Rosetta Code 308
About the Author

Christian Ullenboom s tarted 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)


• 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)
• Spring Boot 3 und Spring Framework 6: Professionelle Enterprise‑Anwendungen mit Java
( ISBN‑13: 978‑3836290494)

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.

xiii
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), leads to gradual improvement in skills.
Books and webinars on learning a programming language are available, but reading, learning, prac‑
ticing, and repeating are just one aspect of becoming a successful software developer. To create 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 2300 classes, about 1400 interfaces, around 140 enumerations, approxi‑
mately 500 exceptions, and a few annotation types and records are added to this. However, in practical
terms, only a small subset of these types proves to be relevant. 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 non‑functional requirements clear
because the quality of programs is not just about “doing what it should.” Issues such as correct indentation,
following naming conventions, 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 Java SE standard libraries. 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 exer‑
cises 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 correspond to it.

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

The first set of tasks are 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.
The Java Standard Edition is augmented by numerous frameworks and libraries. However, this
exercise book does not cover specific libraries or Java Enterprise frameworks like Jakarta EE or Spring
(Boot). There are separate exercise books available for these environments. Additionally, the book does
not require the use of tools like profiling tools, as these are beyond the scope of the book.

WORKING WITH THE 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 any‑
where. 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 defini‑
tions make this clear, and more complex programs help to provide context for understanding different
language characteristics. Furthermore, a more complex program can motivate readers 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 elegant. 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 solutions can
also be found on the website https://github.com/ullenboom/captain‑ciaociao. Some solutions contain com‑
ments of the type //tag::solution[], which marks the parts of the solutions printed in the book.
 • Introduction 3

USE OF THE 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, using tools like Maven and Git for
version management, and becoming proficient in an IDE 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 8 remains prevalent 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 17. Not only is this version equipped with Long‑term Support (LTS), but runtime environment pro‑
viders 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 debug‑
ger, 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 environ‑
ments, 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 $. The user’s input is set in bold. Example:

$ java ‑version
java version "17.0.5" 2022‑10‑18 LTS
Java(TM) SE Runtime Environment (build 17.0.5+9‑LTS‑191)
Java HotSpot(TM) 64‑Bit Server VM (build 17.0.5+9‑LTS‑191, 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 unsa‑
vory characters across the globe. Their secret hideout is on the island of Baloo, where the currency of choice
is Liretta. With a crew hailing from all corners of the world, all program outputs be in English, me hearties.
Advanced String
Processing 1
After dealing with basic data types around characters and strings in another chapter, we will now discuss
advanced string processing. The topics are formatted output, regular expressions, and string splitting.
Prerequisites

• Be able to format strings.


• Be able to match, search, and replace with regular expressions.
• Be able to split strings.
• Understand character encodings and UTF‑8.

Data types used in this chapter:

• java.util.Formatter
• java.lang.String
• java.util.regex.Pattern
• java.util.regex.Matcher
• java.util.Scanner

FORMAT STRINGS
There are different ways in Java to format strings, numbers, and temporal data as a string. In the package
java.text, you can find the classes MessageFormat, DateFormat, and DecimalFormat as well
as the class Formatter and in String the method String.format(…). The next tasks can be solved
using the formatting strings from Formatter in a rather easy way.

Build ASCII Table ⭑


Bonny Brain has installed a new app on her Aye Phone that shows her the ASCII alphabet:

$ ascii
Usage: ascii [‑adxohv] [‑t] [char‑alias...]
‑t = one‑line output ‑a = vertical format
‑d = Decimal table ‑o = octal table ‑x = hex table ‑b binary table
‑h = This help screen ‑v = version information
Prints all aliases of an ASCII character. Args may be chars, C \‑escapes,
English names, ^‑escapes, ASCII mnemonics, or numerics in decimal/octal/hex.

6 DOI: 10.1201/9781003495550-2
1 • Advanced String Processing 7

Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex
0 00 NUL 16 10 DLE 32 20 48 30 0 64 40 @ 80 50 P 96 60 ' 112 70 p
1 01 SOH 17 11 DC1 33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q
2 02 STX 18 12 DC2 34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r
3 03 ETX 19 13 DC3 35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s
4 04 EOT 20 14 DC4 36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t
5 05 ENQ 21 15 NAK 37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u
6 06 ACK 22 16 SYN 38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v
7 07 BEL 23 17 ETB 39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w
8 08 BS 24 18 CAN 40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x
9 09 HT 25 19 EM 41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y
10 0A LF 26 1A SUB 42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z
11 0B VT 27 1B ESC 43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B {
12 0C FF 28 1C FS 44 2C , 60 3C <   76 4C L 92 5C \ 108 6C l 124 7C |
13 0D CR 29 1D GS 45 2D ‑ 61 3D =   77 4D M 93 5D ] 109 6D m 125 7D }
14 0E SO 30 1E RS 46 2E . 62 3E >   78 4E N 94 5E ^ 110 6E n 126 7E ~
15 0F SI 31 1F US 47 2F / 63 3F ?     79 4F O 95 5F _ 111 6F o 127 7F DEL

However, their Aye Phone doesn’t have such a widescreen, and the first two blocks are not visible char‑
acters anyway.

Task:

• Write a program that prints all ASCII characters from position 32 to 127 in the same formatting
as the Unix program ascii does.
• At position 127, write DEL.
8 Java Programming Exercises

Aligned Outputs ⭑
Captain CiaoCiao needs a table of the following type for a listing:

Dory Dab paid


Bob Banjo paid
Cod Buri paid
Bugsy not paid

Task:

• Write a method printList(String[] names, boolean[] paid) that prints a collec‑


tion on the screen. The first string array contains all names, the second array contains informa‑
tion whether the person has paid or not.
• All names can be of different lengths, but the texts in the second column should be aligned.
• The longest string in the first column has a distance of four spaces to the second column.
• If passed arrays are null, a NullPointerException must be thrown.

REGULAR EXPRESSIONS AND


PATTERN RECOGNITION
Regular expressions are a curse and a blessing for many. Used incorrectly, they lead to programs that are
impossible to read later, used correctly, they shorten the program massively and contribute to clarity.
The next exercises will show that we can use regular expressions to test whether

1. A string completely matches a regular expression.


2. A partial string exists and if so, find out where, and then replace it.

Later, we will also use regular expressions to specify separators and decompose strings.

Quiz: Define Regex ⭑


What does the regex look like to match or find the following?

• A string of exactly 10 digits.


• A string of 5–10 digits and letters.
• A string ending in ., ! or ? like a sentence.
• A nonempty string that does not contain digits.
• An official title or a name title: Prof., Dr., Dr. med., Dr. h.c. in the string.

Determine Popularity in Social Media ⭑


Of course Captain CiaoCiao is active on social media; his identifier is #CaptainCiaoCiao or @
CaptainCiaoCiao.
Now Captain CiaoCiao wants to know how popular he is.
1 • Advanced String Processing 9

Task:

• Given an aggregated text with messages; how often does #CaptainCiaoCiao or @


CaptainCiaoCiao occur there?

Example:

• For the following input, the result is 2.


Make me a baby #CaptainCiaoCiao
Hey @CaptainCiaoCiao, where is the recruitment test?
What is a hacker's favorite pop group? The Black IP's.

Detect Scanned Values ⭑


Bonny Brain receives scanned lists of numbers that need to be processed electronically. In the first step,
it sends the scans through an OCR recognizer, and the result is ASCII text. The numbers from the OCR
recognition always look like this:
Representation of the numbers 0 to 9

000 11 22 333 4 4 5555 6 77777 888 9999


0 00 111 2 2 3 4 4 5 6 7 8 8 9 9
0 0 0 11 2 33 4444 555 6666 7 888 9999
00 0 11 2 3 4 5 6 6 7 8 8 9
000 11l1 2222 333 4 555 666 7 888 9
10 Java Programming Exercises

Task:

• Given is a line from the scan with numbers from the format shown. Convert the numbers to an
integer.
• There could be missing spaces after the last digit, and there could be several spaces between
the large characters.

Example:

• If the string (written in the text block syntax) is


String ocr = """
4 4 77777 11 11 4 4 22
4 4 7 111 111 4 4 2 2
4444 7 11 11 4444 2
4 7 11 11 4 2
4 7 11l1 11l1 4 2222""";
so the desired result should be 471142.

If you want to play around with the strings, you can find a way at https://patorjk.com/software/taag/#p=
display&f=Alphabet&t=0123456789.

Quiet Please! Defuse Shouting Texts ⭑


Captain CiaoCiao often gets letters, and the senders often SCREAM in capital letters—how nasty for his
eyes.

Task:

• Write a method String silentShoutingWords(String) that converts all capitalized


words over three letters in length to lowercase.
1 • Advanced String Processing 11

Example:

• silentShoutingWords("AY Captain! Smutje MUST GO!") → "AY Captain!


Smutje must GO!"

Converting Time from AM/PM Format


to 24‑Hour Format ⭑⭑
Bonny Brain frequently gets messages where the time is given in AM and PM.

We raid the harbor at 11:00 PM and meet on the amusement mile at 1:30 AM.

Bonny Brain doesn’t like that; she wants only the 24‑hour count of Military Time.

Task:

• Write a converter that converts strings with AM/PM (case‑insensitive, even with periods) to
Military Time. As a reminder, 12:00 AM is 00:00, and 12:00 PM is 12:00.

Examples:

• "Harbour: 11:00 PM, entertainment districts: 1:30 a.m.!" → Harbour:


2300, entertainment districts: 0130!"
• "Get out of bed: 12:00AM, bake a cake: 12 PM." → "Get out of bed:
0000, bake a cake: 1200"
12 Java Programming Exercises

DECOMPOSE STRINGS INTO TOKENS


Tokenizing is the opposite of constructing and formatting a string. A string is split into substrings, with
separators determining the separation points. Java provides various classes for tokenizing strings and
input. The separators can be symbols or strings described by regular expressions. The split(…) method
of the String class works with regular expressions just like the Scanner, and the StringTokenizer
class does not.

Split Address Lines with the StringTokenizer ⭑


The software of Captain CiaoCiao has to evaluate addresses consisting of three or four lines.
The meaning of the lines

LINE CONTENT OPTIONAL


1 name no
2 street no
3 city no
4 country yes

The lines are separated with a line break. There are four valid separator symbols or sequences:
LF is the abbreviation for “line feed” and CR for “carriage return”; in old teleprinters, CR moved the
carriage to the first column, and LF pushed the paper up.
Traditionally, DOS and Microsoft Windows use the combination \r\n, while Unix systems use \n.
Task:

• Break a newline‑separated string into four lines, and assign the lines to the variables name,
street, city, and country.
• If a fourth line with the country name is not given, let country be "Drusselstein".
• Reassemble the line as a CSV line separated by semicolons.

Examples:

• "Boots and Bootles\n21 Pickle Street\n424242 Douglas\nArendelle" →


Boots and Bootles;21 Pickle street;424242 Douglas;Arendelle
• "Doofenshmirtz Evil Inc.\nStrudelkuschel 4427\nDanville" →
Doofenshmirtz Evil Inc.;Strudelkuschel 4427;Gimmelshtump;
Drusselstein

TABLE 1.1 Line break


CHARACTER
(ABBREVIATION) DECIMAL HEXADECIMAL ESCAPE SEQUENCE
LF 10 0A \n
CR 13 0D \r
CR LF 13 10 0D 0A \r\n
LF CR 10 13 0A 0D \n\r
1 • Advanced String Processing 13

Split Sentences into Words and Reverse Them ⭑


Bonny Brain is waiting for a message, but something went wrong with the transmission—all the words
are reversed!

erehW did eht etarip esahcrup sih kooh? tA eht dnah‑dnoces pohs!

Task:

1. Break the string into words. Separators of words are spaces and punctuation marks.
2. Turn over all the words one by one.
3. Output the words one after the other, separated by a space. The punctuation marks and other
separators are not critical.

Example:

• "erehW did eht etarip esahcrup sih kooh? tA eht dnah‑dnoces pohs!"
→ "Where did the pirate purchase his hook At the hand second shop"

Check Relations between Numbers ⭑


Captain CiaoCiao practices archery, and he records the scores from 0 to 10 in a list. He also notes if he got
better, worse, or if the score stays the same. It may look like this:

1 < 2 > 1 < 10 = 10 > 2

Goldy Goldfish has the task of checking the relation signs <, > and =.
Task:

• Write a program that gets a string like the one in the example and returns true if all relation
signs are correct, and false otherwise.

Examples:

• 1 < 2 > 1 < 10 = 10 > 2 → true


• 1 < 1 → false
• 1 < → false
• 1 → true

Convert A1 Notation to Columns and Rows ⭑⭑


Captain CiaoCiao keeps records of his loot and uses spreadsheets. With his staff, he discusses the figures,
and to address the cells he uses the column and row index; for example, he says 4–16 to refer to the 4th
column and the 16th row. Now he has heard of a whole new way to name cells, A1 notation, which uses a
new kind of software called ECKSEL. This involves coding the column with letters from A to Z, accord‑
ing to the following scheme:

A, B, …, Z, AA, …, AZ, BA, …, ZZ, AAA, AAB, …

The lines are still described with numbers. Thus, A2 stands for cell 1–2.
14 Java Programming Exercises

Since Captain CiaoCiao has its difficulties with A1 notation, the specification is to be converted back
to numeric columns and rows.
Task:

• Write a method parseA1Notation(String) that gets a string in A1 notation and returns


an array with two elements, in which at position 0 is the column and at position 1 is the row.

Examples:

• parseA1Notation("A1") → [1, 1]
• parseA1Notation("Z2") → [26, 2]
• parseA1Notation("AA34") → [27, 34]
• parseA1Notation("BZ") → [0, 0]
• parseA1Notation("34") → [0, 0]
• parseA1Notation(" ") → [0, 0]
• parseA1Notation("") → [0, 0]

Parse Simple CSV Files with Coordinates ⭑


Bonny Brain notes the locations with loot in a CSV file coordinates.csv, where the coordinates are
­floating‑point numbers separated by commas.
For example, the file looks like this:
com/tutego/exercise/string/coordinates.csv

20.091612,‑155.676695
23.087301,‑73.643472
21.305452,‑71.690421

Task:

• Create a CSV file manually. It should contain several lines with coordinates; a comma sepa‑
rates the coordinates.
• A Java program should read the CSV file and output an HTML file with SVG for the polygon
course on the screen.
• Use the class Scanner to parse the file. Make sure to initialize the Scanner with
useLocale(Locale.ENGLISH) if your locale is not English by default.

Example: For the upper block, we want to create

<svg height="210" width="500">


<polygon points="20.091612,‑155.676695 23.087301,‑73.643472 21.305452,‑
71.690421 " style="fill:lime;stroke:purple;stroke‑width:1" />
</svg>

Compress Strings Lossless by Runlength Encoding ⭑⭑⭑


To reduce the volume of data, files are often compressed. There are different compression algorithms;
some are lossy like vowel removal, others work without loss like ZIP. Lossy compression is found in
images, JPEG is a good example. Depending on the degree of compression, the image quality degrades.
In JPEG, very high compression results in an image with strong artifacts.
1 • Advanced String Processing 15

A simple lossless compression is run‑length encoding. The idea is to combine a sequence of ­identical
symbols so that only the number and the symbol are written. The graphic format GIF, for example, uses
this form of compression. Therefore, images with many monochrome lines are also smaller than, for
example, images in which each pixel has a different color.
The next task is about run‑length encoding. Suppose a string consists of a sequence of . (dot) and ‑
(minus sign), such as:

‑‑....‑‑‑‑‑‑‑‑..‑

To shorten the length of strings, we can first write the symbol followed by the number of symbols. The
string with 17 characters could be shortened to the following string with 9 characters:

‑2.4‑8.2‑

Task:

1. Create a new class SimpleStringCompressor.


2. Write a static method String compress(String) that encodes sequences of . and ‑
according to the described algorithm: First comes the character, then the number.
3. Write a decoder String decompress(String) that unpacks the compressed string. Let
decompress(compress(input)) be equal to input.

Extensions:

• The program shall be able to handle all nondigits.


• Refine the program so that the number is omitted if the character occurs only exactly once.

CHARACTER ENCODINGS AND


UNICODE COLLATION ALGORITHM
Over the network and in the file system, everything is stored as a byte. One byte can have 256 different
values, but this is not enough for all the characters in the world. Therefore, there are character encodings,
which can encode all characters in the world in a certain way. The character encodings differ thereby.
Sometimes characters are mapped to a fixed number of bytes, sometimes characters are mapped to a dif‑
ferent number of bytes, or perhaps some characters are just not recognized at all. Java supports all kinds
of character encodings, but the most important character encoding today is the UTF‑8 encoding.

Quiz: Encoding for Unicode Characters ⭑


What characterizes an UTF‑8 encoding?
16 Java Programming Exercises

Quiz: Order of Strings with and without Collator ⭑


After comparing with the Comparator, are the outputs positive, negative, or 0?

Comparator<String> comparator = Comparator.naturalOrder();


System.out.println( comparator.compare( "a", "ä" ) );
System.out.println( comparator.compare( "ä", "z" ) );
System.out.println( comparator.compare( "n", "ñ" ) );
System.out.println( comparator.compare( "ñ", "o" ) );

Comparator<Object> collatorDE = Collator.getInstance( Locale.GERMAN );


System.out.println( collatorDE.compare( "a", "ä" ) );
System.out.println( collatorDE.compare( "ä", "z" ) );
System.out.println( collatorDE.compare( "n", "ñ" ) );
System.out.println( collatorDE.compare( "ñ", "o" ) );

SUGGESTED SOLUTIONS

Build ASCII Table


com/tutego/exercise/string/PrintAsciiTable.java

System.out.println( "Dec Hex ".repeat( 6 ) );

for ( int row = 0; row < 16; row++ ) {


for ( int asciiCode = 32 + row; asciiCode <= 127; asciiCode += 16 ) {
System.out.printf(
"%1$3d %1$X %2$s ", asciiCode,
asciiCode == 127 ? "DEL" : Character.toString( asciiCode ) );
}
System.out.println();
}

First, the program writes the table header, in which the string “Dec Hex” for the six columns is set six
times in a row with spacing.
The generated table has 16 rows, which generates a loop. In principle, we could also dynamically
calculate the number of rows from the start and end values and the number of columns (six in our case).
However, we know that if we start at position 32, and end at 127, with 6 columns we need 16 rows.
The inner loop writes all columns for a given row. At the top left is the first element, the space char‑
acter. To the right, the character increases not by one, but by 16, which is, therefore, the loop counter.
In the next line, we don’t start at 32 but at 33, the pattern here is the following: the start value of the
inner loop is 32 + row, so 32 plus the row number. Altogether, the loop ends when the ASCII code has
reached 127.
Within the inner loop’s body, the character is required to be displayed as a string. Essentially, each
character is outputted as a string. The conditional operator verifies whether the character at positions 127
is the DEL character; all other characters are converted to a string of length 1 through the Character
method. The format string consists of three components: the first two parts access the first format argu‑
ment and begin by displaying the character’s position as a decimal number, followed by its number in
hexadecimal format. The integer is left‑padded with white space, while the hexadecimal number doesn’t
1 • Advanced String Processing 17

require any width information, as it always contains two digits when starting with 32. The third block
contains the character as a string and the second format argument. Finally, a line feed is added at the end
of the line.
Output of PrintAsciiTable

Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex
32 20 48 30 0 64 40 @ 80 50 P 96 60 ' 112 70 p
33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q
34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r
35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s
36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t
37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u
38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v
39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w
40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x
41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y
42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z
43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B {
44 2C , 60 3C <    76 4C L 92 5C \ 108 6C l 124 7C |
45 2D ‑ 61 3D =    77 4D M 93 5D ] 109 6D m 125 7D }
46 2E . 62 3E >    78 4E N 94 5E ^   110 6E n 126 7E ~
47 2F / 63 3F ?     79 4F O 95 5F _   111 6F o 127 7F DEL

Aligned Outputs
com/tutego/exercise/string/PaidOrNotPaid.java

public static void printList( String[] names, boolean[] paid ) {

if ( names.length != paid.length )
throw new IllegalArgumentException(
"Number of names and paid entries are not the same, but "
+ names.length + " and " + paid.length );

int maxColumnLength = 0;
for ( String name : names )
maxColumnLength = Math.max( maxColumnLength, name.length() );

String format = "%‑" + maxColumnLength + "s %spaid%n";

for ( int i = 0; i < names.length; i++ )


System.out.printf( format, names[ i ], paid[ i ] ? "" : "not " );
}

First, the method checks if the two arrays have an equal number of elements, and if not, an
IllegalArgumentException is thrown. Accessing length generates the desired
NullPointerException if the arrays are null.
Since it is unknown in advance how wide the first left column will be, we have to go over all the
strings and determine the maximum length. Using this maximum maxColumnLength we can build a
format string. The format string gets a format specifier that determines the width of a string, padded with
spaces. The format string has a leading minus sign, so this gives a left‑aligned string that is padded on the
18 Java Programming Exercises

right with spaces up to the maximum length maxColumnLength. In addition, the format string contains
a space to the right column of four spaces.
The right column contains either “paid” or “not paid”. That is, the string “paid” always occurs,
and only the word “not” is to be set dependent on a boolean value. This is done by the condition opera‑
tor, which either returns an empty string or the string “not” as a format argument for the format string.

Quiz: Define Regex


com/tutego/exercise/string/RegexExamples.java

// A string of exactly 10 digits

var p1 = Pattern.compile( "\\d{10}" );


out.println( p1.matcher( "0123456789" ).matches() ); // true
out.println( p1.matcher( "1" ).matches() ); // false
out.println( p1.matcher( "sauma ovo" ).matches() ); // false

// A string of 5 to 10 numbers and letters.

var p2 = Pattern.compile( "\\w{5,10}" );


out.println( p2.matcher( "01234567" ).matches() ); // true
out.println( p2.matcher( "0" ).matches() ); // false
out.println( p2.matcher( "01234567890123" ).matches() ); // false

// A string that ends with `.`, `!` or `?`, like a sentence.

var p3 = Pattern.compile( ".*[.!?]$" );


out.println( p3.matcher( "jes? jes!" ).matches() ); // true
out.println( p3.matcher( "ne?" ).matches() ); // true
out.println( p3.matcher( "okej." ).matches() ); // true
out.println( p3.matcher( "se vi diras tion" ).matches() );// false

// A string that contains no digits.

var p4 = Pattern.compile( "\\D*" );


out.println( p4.matcher( "Ciao" ).matches() ); // true
out.println( p4.matcher( "Cia0" ).matches() ); // false
out.println( p4.matcher( "" ).matches() ); // true

// Contains an official title, Prof., Dr., Dr. med., Dr. h.c.

var p5 = Pattern.compile( "(Prof\\.|Dr\\. med\\.|Dr\\. h\\.c\\.|Dr\\.)\\s" );


out.println( p5.matcher( "Saluton Sinjoro Dr. Miles" ).find() ); // true
out.println( p5.matcher( "ne korekta Dr. h.c. Thai med." ).find() );// true
out.println( p5.matcher( "Megan Dr.Thai" ).find() ); // false

In the last example, it is about finding and not about a complete match, so the find() method of Matcher
is used. In principle, tests of existence can also be formulated by .*FIND.* and matches(…), but match‑
ing makes a little more work for the regex engine than just providing the first find and not having to look
to the end.
1 • Advanced String Processing 19

Determine Popularity in Social Media


com/tutego/exercise/string/Popularity.java

String text = """


Make me a baby #CaptainCiaoCiao
Hey @CaptainCiaoCiao, where is the recruitment test?
What is a hacker's favorite pop group? The Black IP's.""";

var pattern = Pattern.compile( "[#@]CaptainCiaoCiao" );


System.out.println( pattern.matcher( text ).results().count() );

The task can be solved with a one‑liner because the Matcher method results() returns a
Stream<MatchResult>, and for Stream objects the count() method determines the number of
occurrences.

Detect Scanned Values


com/tutego/exercise/string/OcrNumbers.java

private final static String[] searches = {


"000", "11", "22", "333", "44", "55555", "6", "77777", "888", "9999" };

private static int parseOcrNumbers( String string ) {


String line = new Scanner( string ).nextLine().replaceAll( "\\s+", "" );

for ( int i = 0; i < searches.length; i++ )


line = line.replaceAll( searches[ i ], "" + i );

return Integer.parseInt( line );


}

If we take a closer look at the big numbers, we quickly realize that each large number contains the actual
number itself. The large zero contains 0, the large one contains 1, and so on. So, we don’t have to evaluate
several lines, it’s enough to take any line. We just take the first one.
After extracting the first line, we can search for the substring that makes up the single digits. The
blanks interfere a bit, so they are removed in the first step. A new String is created from the first line,
in which all spaces have been removed, and then the digits of each major character are aligned. For
example, if the line starts with 000, we know that the first digit in the result must be 0. We can simply
use replaceAll(…) to replace the sequence 000 with 0. For example, if there are two zeros in a row,
0000 correctly becomes 00.
Since not only three zeros have to be replaced by zero, but also two ones by a one, and there are ten
different replacements, we store the individual strings in an array beforehand. A loop runs through the
array, and in the body, there are repeated calls to replaceAll(…), which replaces all partial strings
from the search with the loop index, so that, for example, 000 becomes "" + 0, i.e., "0". At the end, we
convert the number to an integer and return the result.
If the incoming string is null, empty, or contains foreign characters, there will be exceptions in the
following. This behavior is fine.
20 Java Programming Exercises

Quiet Please! Defuse Shouting Texts


com/tutego/exercise/string/DoNotShout.java

public static String silentShoutingWords( String string ) {


return Pattern.compile( "\\p{javaUpperCase}{3,}" )
.matcher( string )
.replaceAll( matchResult ‑> matchResult.group().toLowerCase() );
}

The proposed solution proceeds in three steps: Building the pattern object, matching the string, and
replacing the match group with lowercase strings. The regex string must describe a sequence of uppercase
letters. Upper case letters, over the entire Unicode alphabet, determine \p{javaUpperCase}. We want
to have at least three uppercase letters in a row, which {3,} takes care of. Whether to keep the pattern
precompiled in a static variable depends entirely on how often the method is called. In general, it is a good
strategy to keep the Pattern objects in memory because translation always costs a little execution time.
On the other hand, you reference an object, and if you rarely need it, you don’t have to.
The method compile(…) gives us a Pattern object, and the matcher(…) method gives us a
Matcher object. We can well use the replaceAll(Function<MatchResult, String>) method,
which can perform a transformation of the found strings. The argument passed is a function that maps a
MatchResult to a string. Our function accesses the group, converts the string to lowercase, and returns
it. replaceAll(…) finds all places with the selected uppercase letters and calls this function mul‑
tiple times.

Converting Time from AM/PM


Format to 24‑Hour Format
com/tutego/exercise/string/AmPmToMilitaryTime.java

private static final Pattern AM_PM_PATTERN =


Pattern.compile( "(?<hours>\\d\\d?)" + // hours
"(?::(?<minutes>\\d\\d))?" + // minutes
"\\s?" + // optional whitespace
"(?<ampm>[ap])[.]?m[.]?", // AM/PM
Pattern.CASE_INSENSITIVE );

public static String convertToMilitaryTime( String string ) {


Matcher matcher = AM_PM_PATTERN.matcher( string );
return matcher.replaceAll( matchResult ‑> {
int hours = Integer.parseInt( matcher.group( "hours" ) );
int minutes = matcher.group( "minutes" ) == null ?
0 :
Integer.parseInt( matcher.group( "minutes" ) );
boolean isTimeInPm = "pP".contains( matcher.group( "ampm" ) );
if ( isTimeInPm && hours < 12 ) hours += 12;
else if ( !isTimeInPm && hours == 12 ) hours ‑= 12;
return String.format("%02d%02d", hours, minutes);
} );
}
1 • Advanced String Processing 21

At the heart of the program is a regular expression that captures times. This regular expression consists of
four parts, which are also split into four lines in the code. The first part captures the hours, the part cap‑
tures the minutes, the third part is an optional white space between the time, and the last part, AM/PM.

1. The hours consist of at least one integer, the second integer being optional if, for example, 1
AM is written. In principle, we could write the expression a bit more precisely so that something
like 99 AM is not recognized, but we do not make that check here. The hours themselves are in
round brackets, a group named ?<hours>. All regular expression groups can be named so that
we can access them more easily later by that name and not have to use a group index.
2. The minute’s part is optional, that is, it is enclosed in round brackets altogether, and there is a
question mark at the end. The inside starts with a ?:, which is a small regular expression opti‑
mization so that this group is inaccessible via the API later. If hours and minutes are specified
at the same time, a colon separates them. The minutes themselves are also a named group, and
they consist of two decimal numbers. Again, we do not make any checks about possible ranges
of validity.
3. The third part is a white space, which is optional.
4. The last part must capture different notations of AM/PM. A dot could be placed between the
two symbols, perhaps even mistakenly just after a letter, so say A.M or AM. So that we don’t
have to specify case, we include a special pattern flag that checks case independently, so it
doesn’t matter whether we write AM, am, Am, or pM.

The convertToMilitaryTime(String) method gets the string with the time information as a
parameter. The Pattern object was stored as a constant, and the matcher(…) method connects the
Pattern with the string method parameter. The result is a Matcher. This type can do all the work
with replaceAll(Function<MatchResult, String> replacer): the method runs over all the
matches for us, calls our Function, and we can access the match from the MatchResult and replace
it with a string.
Regarding the Function: first, we access the group for the hours and convert it to an integer.
Converting an integer will not throw an exception because our regular expression ensures that only digits
occur. The peculiarity with minutes is that they can be missing. So, we have to go back to the group min‑
ute and ask if it exists at all. If it does not exist, we assign the variable minutes with 0; otherwise, we
convert the string with the minutes into an integer and set the variable minutes with it.
Now we evaluate the group ampm and declare a variable isTimeInPm, which becomes true if the
time is given in PM. For AM, the variable remains false. This variable helps with the conversion. If
isTimeInPm is true, then the time is “post meridiem”, i.e., afternoon, and 12 hours must be added. It
may happen that the text mistakenly enters 23 PM, for example; in this case, we want to correct the error
and do not add 12. Moreover, if the time of the hours is equal to 12 o`clock, we also do not correct. The
next check is specifically for 12:xx, which becomes 00xx clock. So, if isTimeInPm equals false,
then it is the time “ante meridiem”, that is the morning, and we subtract 12.
After the two variables hours and minutes are set, we generate a string with the hours and min‑
utes and use String.format(…) so that we get the times with only one digit padded with a 0. This is
the return of the Function.

Split Address Lines with the StringTokenizer


com/tutego/exercise/string/SplitAddressLines.java

// String address = "Boots and Bootles\n21 Pickle Street\r\n424242 Douglas\


rArendelle";
String address="Doofenshmirtz Evil Inc.\nStrudelkuschel 4427\nGimmelshtump";
22 Java Programming Exercises

StringTokenizer lines = new StringTokenizer( address, "\n\r" );


String name = lines.nextToken();
String street = lines.nextToken();
String city = lines.nextToken();
final String DEFAULT_COUNTRY = "Drusselstein";
String country = lines.hasMoreTokens() ? lines.nextToken() : DEFAULT_COUNTRY;

System.out.println( name + ";" + street + ";" + city + ";" + country );

In the center of the job is the class StringTokenizer, which is useful whenever.

1. Not (all) tokens are to be extracted in advance like with split(…), but step by step.
2. The separators consist of single characters, but no strings.

Similarly, we create an instance of StringTokenizer, but it’s important to note that the two specified
characters are not treated as a combined separator; instead, they are considered as individual characters
that can serve as a separator for the tokens in any combination.
With the method nextToken() we ask for the lines three times, and since we don’t know if there is
a fourth line, we look ahead with hasMoreTokens(). If there is a token, we consume it. Otherwise, we
choose the desired default country.
Since StringTokenizer is an Enumeration<Object>, in principle we could have used
hasMoreElements() and nextElement(), but the latter method has the awkward Object return
type.

Split Sentences into Words and Reverse Them


Let’s start with a small helper method that prints words reversed:
com/tutego/exercise/string/PrintReverseWords.java

private static void printWordReversed( String word ) {


System.out.print( new StringBuilder( word ).reverse() );
System.out.print( ' ' );
}

The reversing of the string is done by the reverse(…)‑ method of the StringBuilder. We then out‑
put the result to the screen, separated by a space at the end.
Now we have to split the sentence and recognize the words.
com/tutego/exercise/string/PrintReverseWords.java

String string = "erehW did eht etarip esahcrup sih kooh? tA eht dnah‑dnoces pohs!";

String pattern = "[\\p{Punct}\\s]+";

new Scanner( string )


.useDelimiter( pattern )
.forEachRemaining( PrintReverseWords::printWordReversed );

System.out.println();

for ( String word : string.split( pattern ) )


printWordReversed( word );
1 • Advanced String Processing 23

At the center is the regular expression [\p{punct}\s]+. It captures a sequence of punctuation marks,
parentheses, etc., and white space separating words. We make use of predefined character classes. It uses
\p{punct} for a character out of

!"#$%&'()*+,‑./:;<=>?@[\]^_'{|}~

and \s for the white space; it is the character class [ \t\n\x0B\f\r]. For a connection, we put both
into a new character class, and since characters can occur any number of times in a row, we add a plus.
Java supports splitting with regular expressions via the Pattern‑Matcher combination, and two
well‑known facades are the Scanner and the split(…) method. Both variants are shown in the pro‑
posed solution. The Scanner is always good if the number of matches can be large because with the
split(…) method the answer is always an array with all words. The Scanner implements Iterable
and at forEachRemaining(…) we put a method reference to the helper method printWordRe‑
versed(…) for the Consumer, which writes each word reversed on the screen.

Check Relations between Numbers


com/tutego/exercise/string/RelationChecker.java

private static boolean isValidRelation( int number1, String operator,


int number2 ) {
return switch ( operator ) {
case ">" ‑> number1 > number2;
case "<" ‑> number1 < number2;
case "=" ‑> number1 == number2;
default ‑> false;
};
}

public static boolean isValidRelation( String string ) {


Scanner scanner = new Scanner( string );
int number1 = scanner.nextInt();

while ( scanner.hasNext() ) {
String operator = scanner.next();
int number2 = scanner.nextInt();
if ( isValidRelation( number1, operator, number2 ) )
number1 = number2;
else
return false;
}

return true;
}

The actual method checkRelation(String) gets the string and checks the relations. However, the
method falls back on its own private method isValidRelation(int, String, int) so we want
to start with that. isValidRelation(…) gets a number, a comparison operator, and another number. It
checks if the comparison operator with the two numbers returns a true result. If so, the answer is true; if
the comparison is false, the answer is false just as in the case of a misplaced symbol because we evalu‑
ate only <, > and =.
24 Java Programming Exercises

The method checkRelation(…) builds a Scanner with the passed String and now uses a
combination of nextInt(), hasNext(), and next() to process tokens from the Scanner. At the
beginning, there must always be a number, which means we can initialize a variable number1 with the
first number. The data stream could be empty now, but if the Scanner has the next symbols, this will be
a comparison operator, which we will refer to. After the comparison operator comes to a second integer,
which we also read in and store in number2. Now we call our method isValidRelation(…), and this
method returns true if the comparison was fine. Then number2 will become the new number1, so in
the next loop pass, number2 will be assigned the following number. If isValidRelation(…) returns
false, then we can abort the method because at this point the comparison is false. If there was no break‑
out from the loop, all comparisons were correct, and the method ends with return true.

Convert A1 Notation to Columns and Rows


com/tutego/exercise/string/A1Notation.java

private static final int NUMBER_OF_LETTERS = 26;

private static int parseColumnIndex( String string ) {


int result = 0;
for ( int i = 0; i < string.length(); i++ ) {
// Map A..Z to 1..26
int val = Character.getNumericValue( string.charAt( i ) ) ‑ 9;
result = NUMBER_OF_LETTERS * result + val;
}
return result;
}

public static int[] parseA1Notation( String cell ) {


Matcher matcher = Pattern.compile( "([A‑Z]+)(\\d+)" ).matcher( cell );
if ( ! matcher.find() || matcher.groupCount() != 2 )
return new int[]{ 0, 0 };
int column = parseColumnIndex( matcher.group( 1 ) );
int row = Integer.parseInt( matcher.group( 2 ) );
return new int[]{ column, row };
}

Let us consider the cell AA34 mentioned in the task as an example. In the first step, we need to separate
the column from the row. The column here would be AA, the row 34. We then need to convert the column
AA to the numeric representation, 27. Two separate methods handle these two steps. The main method
parseA1Notation(String) first extracts the row and column, and then calls an internal method
parseColumnIndex(String), which converts the column to a numeric value for us after the A1
notation.
Let’s start with the parseColumnIndex(String) method. We’ll take a few examples to make it
easier to read the calculation pattern.
What we can read is the following:

• Each letter is transferred to a number—A to 1, B to 2 until finally Z to 26.


• The example is a place value system. It is similar to our decimal system, but here the factor 26
is used as a multiplier.
1 • Advanced String Processing 25

TABLE 1.2 Calculation of A1 notation


SYMBOL SEQUENCE CALCULATION RESULT
A 1 × 260   1
Z 26 × 260 26
AA 1 × 261 + 1 × 260 27
IV 9 × 261 + 22 × 260 256
AAA 1 × 262 + 1 × 261 + 1 × 260 703

To convert the whole thing now into an algorithm, we use the Horner scheme. Let us illustrate this with
an example:

WDE = 23 × 262 + 4 × 261 + 5 × 260 = ((23 × 26) + 4) × 26 + 5

The Horner scheme is important for us because we don’t need to calculate powers anymore. If we go one
place further to the right, we multiply the old result by 26 and repeat the scheme for the other places. This
is precisely what the method parseColumnIndex(String) does. A loop runs over all characters,
extracts them, and queries the numeric representation with Character.getNumericValue(char).
This is defined not only for digits but also for letters. For the letter 'a' the result is 10, the same as for
'A'. For 'Z' it is 35. If we subtract 9 from this, we get the range of values 1–26. We take the old result,
multiply it by 26, and add the numeric representation of the letter. The next step is to calculate the new
numeric value of the next character, multiply the last result by 26, and again add the value of the last letter.
This performs the calculation exactly as we planned it.
The method parseA1Notation(String) has little work to do. First, we compile a Pattern that
extracts the column and row—since the column is all letters and the row is all digits, we can easily capture
that via the groups in the regular expression. If the string is wrong, and if we don’t have two matches, we
return an array of {0, 0}, signaling incorrect input. If there are two match groups, we take the column
information from the first one and convert it to an integer using our own parseColumnIndex(String)
method. The second string, according to the regular expression, is a valid string of digits, which Integer.
parseInt(String) converts to an int. The numeric column and row go into a small array, and that
goes back to the caller.

Parse Simple CSV Files with Coordinates


com/tutego/exercise/string/GenerateSvgFromCsvCoordinates.java

String filename = "coordinates.csv";


try ( InputStream is =
GenerateSvgFromCsvCoordinates.class.getResourceAsStream( filename );
Scanner scanner = new Scanner( is, StandardCharsets.ISO_8859_1 ) ) {
scanner.useDelimiter( ",|\\s+" ).useLocale( Locale.ENGLISH );

StringBuilder svg = new StringBuilder( 1024 );


svg.append( "<svg height=\"210\" width=\"500\">\n<polygon points=\"" );

while ( scanner.hasNextDouble() ) {
double x = scanner.nextDouble();

if ( ! scanner.hasNextDouble() )
throw new IllegalStateException( "Missing second coordinate" );
Exploring the Variety of Random
Documents with Different Content
rhythm of one's life and my life is very rhythmic just now. Do you
remember, one night at the villa, there was some conversation about
formulæ and black magic?
You mean the contessa....
She was speaking figuratively, perhaps, but I have taken her literally.
He paused for a moment; then he continued, It is possible that you
will also remember my telling you in Florence that I believed
Donatello's David to be the most beautiful work of art in the world.
I remember; I still think you were right.
I haven't altered my opinion. It is the most beautiful statue I have
ever seen, just as Debussy's l'Après-midi d'un Faune is the most
beautiful music I have ever heard, just as The Hill of Dreams is—
have you read it?
At that time, I had not, and I admitted it. I was even ignorant of the
name of the author.
Now Peter, as he sat on the bench beside me, began to speak of
Arthur Machen: The most wonderful man writing English today and
nobody knows him! His material is handled with the most
consummate art; arrangement, reserve, repose, the perfect word,
are never lacking from his work and yet, at the age of fifty, he is an
obscure reporter on a London newspaper. There are, of course,
reasons for this neglect. It is a byword of the day that one only takes
from a work of art what one brings to it, and how few readers can
bring to Machen the requisite qualities; how few readers have
gnosis!
Machen evokes beauty out of horror, mystery, and terror. He
suggests the extremes of the terrible, the vicious, the most evil, by
never describing them. His very reserve conveys the infinity of
abomination. You know how Algernon Blackwood documents his
work and stops to explain his magic orgies, so that by the time you
have finished reading one of his weird stories, you completely
discount it. On the other hand, although Machen writes in the
simplest English concerning the most unbelievable impieties, he
never lifts the crimson curtain to permit you to see the sacrifice on
the Manichean altar. He leaves that to the imagination. But his
expression soars so high, there is such ecstasy in his prose, that we
are not meanly thrilled or revolted by his negromancy; rather, we are
uplifted and exalted by his suggestion of impurity and corruption,
which leads us to ponder over the mysterious connection between
man's religious and sensual natures. Think, for a moment, of the life
of Paul Verlaine, dragged out with punks and pimps in the dirtiest
holes of Paris, and compare it with the pure simplicity of his religious
poetry. Think of the Song of Songs which is Solomon's and the
ancient pagan erotic rites in the holy temples. Remember the Eros of
the brothels and the Eros of the sacred mysteries. Recall the
Rosicrucian significance of the phallus, and its cryptic perpetuation in
the cross and the church steeple. In the middle ages, do not forget,
the Madonna was both the Virgin Mother of Christ and the patron of
thieves, strumpets, and murderers. Far surpassing all other
conceivable worldly pleasures is the boon promised by the
gratification of the sensual appetite; faith promises a bliss that will
endure for ever. In either case the mind is conscious of the
enormous importance of the object to be obtained. Machen achieves
the soaring ecstasy of Keats's Ode on a Grecian Urn or Shelley's To
a Skylark, and yet he seldom writes of cool, clean, beautiful things.
Was ever a more malignantly depraved story written than The White
People (which it might be profitable to compare with Henry James's
The Turn of the Screw), the story of a child who stumbles upon the
performance of the horrid, supernatural rites of a forgotten race and
the consequences of the discovery? Yet, Machen's genius burns so
deep, his power is so wondrous, that the angels of Benozzo Gozzoli
himself do not shine with more refulgent splendour than the outlines
of this erotic tale, a tale which it would have been easy to vulgarize,
which Blackwood, nay Poe himself, would have vulgarized, which
Laforgue would have made grotesque or fantastic, which Baudelaire
would have made poetic but obscene. But Machen's grace, his rare,
ecstatic grace, is perpetual and unswerving. He creates his rhythmic
circles without a break, the skies open to the reader, and the Lord,
Jesus Christ, appears on a cloud, or Buddha sits placidly on his
lotus. Even his name is mystic, for, according to the Arbatel of Magic,
Machen is the name of the fourth heaven.
Machen does not often write of white magic; he is a negromancer;
the baneful, the baleful, the horrendous are his subjects. With
Baudelaire, he might pray, Evil be thou my good! Consider the theme
of The Great God Pan, a psychic experiment, operation, if you will,
on a pure young girl, and its consequences. Again a theme which
another writer, any other writer, would have cheapened, filled in with
sordid detail, described to the last black mass. But Machen knows
better. He knows so much, indeed, that he is able to say nothing. He
keeps the thaumaturgic secrets as the alchemists were bidden to do.
Instead of raising the veil, he drops it. Instead of revealing, he
conceals. The reader may imagine as much as he likes, or as much
as he can, for nothing is said, but he rises from a reading of one of
these books with a sense of exaltation, an awareness that he has
tasted the waters of the Fountain of Beauty. There is, indeed,
sometimes, in relation to this writer, a feeling[3] that he is truly
inspired, that he is writing automatically of the eternal mysteries, that
the hand which holds the pen is that of a blind genius, and yet....
More straightforward good English prose, limpid narrative, I am not
yet acquainted with. What a teller of stories! This gift, tentatively
displayed in The Chronicle of Clemendy, which purports to be a
translation from an old manuscript—Machen has really been the
translator of the Heptamaron, Béroalde de Verville's Moyen de
Parvenir, and the Memoirs of Casanova—, flowered in The Three
Imposters, nouvelles in the manner of the old Arabian authors. This
work is not so well-known as The Dynamiter, which it somewhat
resembles, but it deserves to be. Through it threads the theme, that
of nearly all his tales, of the disintegration of a soul through an
encounter with the mysteries which we are forbidden to know, the
Sabbatic revels, the two-horned goat, alchemy, devil-worship, and
the eternal and indescribable symbols. The problem is always the
same, that of facing the great God Pan and the danger that lurks for
the man who dares the facing.
And one wonders, Peter continued, his eyes dilating with an
expression which may have been either intense curiosity or horror,
one wonders what price Machen himself has paid to learn his secret
of how to keep the secrets! He must have encountered this horror
himself and yet he lives to ask the riddle in flowing prose! What has it
cost him to learn the answer? Popularity? Perhaps, for he is an
obscure reporter on a London newspaper and he drinks beer! That is
all any Englishman I have asked can tell me about him. Nobody
reads his books; nobody has read them ... except the few who see
and feel, and John Masefield is one of these. This master of English
prose, this hierophant, who knows all the secrets and keeps them,
this delver in forgotten lore, this wise poet who uplifts and inspires
us, is an humble journalist and he drinks beer!
Peter paused and looked at me, possibly for corroboration, but what
could I say? I had never, until then, touched upon Machen, although
I remembered that Mina Loy had included him in her catalogue of
protestants in the symposium at the Villa Allegra. Later, when I
sought his books, I found them more difficult to arrive at than those
of any of his contemporaries and today, thanks to the fame he has
achieved through his invention of the mystic story of The Bowmen,
the tale of the Angels at Mons, a story which was credited as true,
for returning soldiers swore that they had really seen these angels
who had led them into battle, thus arousing the inventive pride of the
author, who published a preface to prove that the incident had never
occurred except in his own brain, his early books command fantastic
prices. Eight or nine pounds is asked for The Chronicle of Clemendy
and forty or fifty pounds for his translation of Casanova. But on that
day I said little about the matter, because I had nothing to say.
Now we were walking and presently stopped before Peter's door, a
house on the south side of Stuyvesant Square, conveniently near,
Peter observed, in sardonic reference to Marinetti's millennium, the
Lying-in-Hospital. He unlocked the door and we entered. The hall
was painted black and was entirely devoid of furniture. A lamp,
depending on an iron chain from the ceiling, shed but a feeble glow,
for it was enclosed in a globe of prelatial purple glass. We passed on
to a chamber in which purple velvet curtains were caught back by
heavy silver ropes, exposing at symmetrical intervals, the black
walls, on which there were several pictures: Martin Schongauer's
copperplate engraving of The Temptation of Saint Anthony, in which
the most obscene and foulest of fiends tear and pull and bite the
patient and kindly old man; Lucas Cranach's woodcut of the same
subject, more fantastic but less terrifying; two or three of Goya's
Caprichos; Félicien Rops's Le Vice Suprême, in which a skeleton in
evening dress, holding his head in the curve of his elbow, chapeau
claque in hand, opens wide an upright coffin to permit the
emergence of a female skeleton in a fashionable robe; black ravens
flit across the sky; Aubrey Beardsley's Messalina; Pieter Bruegel's
allegorical copperplate of Lust, crammed with loathsome details; and
William Blake's picture of Plague, in which a gigantic hideous form,
pale-green, with the slime of stagnant pools, reeking with vegetable
decays and gangrene, the face livid with the motley tints of pallor
and putrescence, strides onward with extended arms, like a sower
sowing his seeds, only the germs of his rancid harvest are not cast
from his hands but drip from his fusty fingers. The carpet was black
and in the very centre of the room was a huge silver table,
fantastically carved, the top upheld by four basilisk caryatides. On
this table stood a huge egg, round which was coiled a serpent, the
whole fashioned from malachite, and a small cornelian casket,
engraved in cuneiform characters. There were no windows in the
room, and apparently no doors, for even the opening through which
we had entered had disappeared, but the chamber was pleasantly
lighted with a lambent glow, the origin of which it was impossible to
discover, for no lamps were visible. In one corner, I noted a cabinet
of ebony on the top of which perched an enormous black, short-
haired cat, with yellow eyes, which, at first, indeed, until the animal
made a slight movement, I took to be an objet d'art. Then Peter
called, Lou Matagot, and with one magnificent bound, the creature
landed on the silver table and arched his glossy back. Then he
sharpened his claws and stretched his joints by the aid of the casket
scratched with the cuneiform symbols.
Lou Matagot, Peter explained, signifies the Cat of Dreams, the Cat of
the Sorcerers, in the Provençal dialect.
There were a few chairs, strangely modern, Ballet Russe chairs,
upholstered in magenta and green and orange brocades in which
were woven circles and crescents and stars of gold and silver, but
Peter and I seated ourselves at one end of the room on a high purple
couch, a sort of throne, piled with silver and black cushions, on
which was worked in green threads an emblem, which Peter
explained was the character of Mersilde, a fiend who has the power
to transport you wherever you wish to go. Now, he pulled a silver
rope which hung from the ceiling, the lights flashed off and on again,
and I observed that we were no longer alone. A little black page boy
in a rose doublet, with baggy silver trousers, and a turban of scarlet
silk, surmounted by heron's plumes, sparkling with carbuncles, stood
before us. He had apparently popped out of the floor like the
harlequin in an English pantomime. At a sign from Peter, he pressed
a button in the wall, a little cupboard opened, and he extracted a
bottle of amber crystal, half-full of a clear green liquid, and two
amber crystal glasses with iridescent flanges.
I am striving to discover the secrets, said Peter, as we sipped the
liqueur, the taste of which was both pungent and bitter.
Not in this room! I gasped. Unless you mean the secrets of Paul
Poiret and Léon Bakst.
No, he laughed, as the cat leaped to his shoulder and began to purr
loudly, not in this room. This is my reception-room where I receive
nobody. You are the first person, with the exception of Hadji, to enter
this house since I have remodelled it but, he continued reflectively, I
have a fancy that the bright fiends of hell, the beautiful yellow and
blue devils, will like this room, when I call them forth to do my
bidding.
Again he warned me, Not one word to Edith, do you understand?
Not one word. I must be alone. I have told you and only you. I must
work in peace and that I cannot do if I am interrupted. This room is
my relief. It amuses me to sit here, but it is not my laboratory. Come,
it is time to show you. Besides, I have my reasons....
We did not rise. The lights were again mysteriously extinguished and
I felt that the couch on which we sat was moving. The sensation was
pleasant, like taking a ride on a magic carpet or a taktrevan. In a few
seconds, when light appeared again, instead of a wall behind us we
sat with a wall before us. Facing about, I perceived that we were in
another chamber, a chamber that would have pleased Doctor Faust,
for it was obviously the laboratory of an alchemist. Nevertheless, I
noted at once a certain theatrical air in the arrangement.
This, I said, seems more suitable for the performances of Herrmann
the Great or Houdini than the experiments of Paracelsus.
Peter grinned. It was clear that he was taking a childish delight in the
entertainment.
It is fun to do this with you. I've had no one but the black boy and the
cat. There are moments when I think I would like to bring Edith here,
but she would spoil it by getting tired of it, or else she would like it
too much and want to come every day and bring others with her to
see the show. Well, look around.
I followed his advice. It was the conventional alchemist's retreat.
There were stuffed owls and mummies and astrolabes. Herbs and
bones were suspended from the ceiling. Skulls grinned from the tops
of cabinets. There were rows and rows of ancient books, many of
them bound in sheepskin or vellum, in a case against one wall. A few
larger volumes, with brass or iron clasps, reposed on a table. Lou
Matagot, who had been carried into the room with us, presently
stretched his great, black, glossy length over the top of one of these.
There were cauldrons, retorts, crucibles, rows of bottles, a fire, with
bellows, and a clepsydra, or water-clock, which seemed to be
running. There was an Arcula Mystica, or demoniac telephone,
resembling a liqueur-stand. Peter explained that possessors of this
instrument might communicate with each other, over whatever
distance. There were cabinets, on the shelves of which lay amulets
and talismans and periapts, carved from obsidian or fashioned of
blue or green faience, the surfaces of which were elaborately
scratched with hermetic characters, and symplegmata with their
curious confusion of the different parts of different beasts. There
were aspergills, and ivory pyxes, stolen, perhaps, from some holy
place, and now consecrated to evil uses. There were stuffed
serpents and divining rods of hazel. There were scrolls of
parchment, tied with vermilion cord. In fact, there was everything in
this room, that David Belasco would provide for a similar scene on
the stage.
Here, said Peter, I study the Book of the Dead, hierograms,
rhabdomancy, oneiromancy, hippomancy, margaritomancy,
parthenomancy, gyromancy, spodanomancy, ichthyomancy,
kephalonomancy, lampodomancy, sycomancy, angelology,
pneumatology, goety, eschatology, cartomancy, aleuromancy,
alphitomancy, anthropomancy, axinomancy, which is performed by
applying an agate to a red-hot ax, arithmomancy, or divination by
numbers, alectoromantia, in which I lay out the letters of the alphabet
and grains of wheat in spaces drawn in a circle and permit a cock to
select grains corresponding to letters, belomancy, divination by
arrows, ceroscopy, cleidomancy, astragalomancy, amniomancy,
cleromancy, divination performed by throwing dice and observing the
marks which turn up, cledonism, coscinomancy, capnomancy,
divination by smoke, captoptromancy, chiromancy, dactyliomancy,
performed with a ring, extispicium, or divination by entrails,
gastromancy, geomancy, divination by earth, hydromancy, divination
by water, and pyromancy and æromancy, divination by fire and air,
onomancy, divination by the letters of a name, onychomancy, which
is concerned with finger-nails, ornithomancy, which deals with birds,
and chilomancy, which deals with keys, lithomancy, eychnomancy,
ooscopy, keraunoscopia, bibliomancy, myomancy, pan-psychism,
metempsychosis, the Martinists, the Kabbalists, the Diabolists, the
Palladists, the Rosicrucians, the Luciferians, the Umbilicamini, all the
nocuous, demonological, and pneumatic learning, including
transcendental sensualism. At present, I am experimenting with
white mice. I dip their feet in red ink and permit them to make
scrawls on a certain curious chart.
I have dabbled in drugs, for you know that the old Greek priests, the
modern seers, and the mediæval pythonesses, all have resorted to
drugs to assist them to see visions. The narcotic or anæsthetic
fumes, rising from the tripods, lulled the old Greek hierophants and
soothsayers into a sympathetic frame of mind. First, I experimented
with Napellus, for I had read that Napellus caused one's mental
processes to be transferred from the brain to the pit of the stomach.
There exists an exact description of the effects of this drug on an
adept, one Baptista Van Helmont, which I will read you.
Peter, here, went to the shelves, and after a little hesitation, pulled
out an old brown volume. He turned over the pages for a few
seconds and then began to read: Once, when I had prepared the
root (of Napellus) in a rough manner, I tasted it with the tongue:
although I had swallowed nothing, and had spit out a good deal of
the juice, yet I felt as if my skull was being compressed by a string.
Several household matters suggested themselves and I went about
the house and attended to them. At last, I experienced what I had
never felt before. It seemed to me that I neither thought nor
understood, and as if I had none of the usual ideas in my head; but I
felt, with astonishment, clearly and distinctly, that all these functions
were taking place at the pit of the stomach: I felt this clearly and
perfectly, and observed with the greatest attention that, although I
felt movement and sensation spreading themselves over the whole
body, yet that the whole power of thought was really and
unmistakably situated in the pit of the stomach, always excepting a
sensation that the soul was in the brain as a governing force. The
sensation was beyond the power of words to describe. I perceived
that I thought with greater clearness: there was a pleasure in such
an intellectual distinctness. It was not a fugitive sensation; it did not
take place while I slept, dreamed, or was ill, but during perfect
consciousness. I perceived clearly that the head was perfectly
dormant as regarded fancy: and I felt not a little astonished at the
change of position.
Well, continued Peter, closing the book and regarding me with great
intensity, you will admit that would be a sensation worth
experiencing. So I tried it ... with horrible results. Will you believe it
when I tell you that I became wretchedly ill in that very centre which
Van Helmont locates as the seat of thought? I suffered from the most
excruciating pains, which were not entirely relieved by an emetic.
Indeed, I passed a week or so in bed.
My next experiment, he went on, was made with hashish, Cannabis
Indica, which I prepared and took according to the directions of
another adept, who had found that the drug produced a kind of
demoniac and incessant laughter, hearty, Gargantuan laughter, and
the foreshortening of time and space. He could span the distance
between London and Paris in a few seconds. Furniture and statues
assumed a comic attitude; they seemed to move about and become
familiar with him. He was literally aware of what the Rosny have
called the "semi-humanité des choses." I took the drug, as I have
said, exactly as he directed, but the effect on me was entirely
dissimilar. Immediately, I was plunged into immoderate melancholy.
The sight of any object immeasurably depressed me. I also noted
that my legs and arms had apparently stretched to an abnormal
length. I sobbed with despair when I discovered that I could scarcely
see to the other end of my laboratory, it seemed so far away.
Mounting the stairs to my bed-chamber was equivalent in my mind to
climbing the Himalayas. Although Hadji afterward assured me that I
had been under the influence of the drug for only fourteen hours, it
was more like fourteen years to me, which I had passed without
sleep. At the end of the experiment, my nerves revolted under the
strain and again I was forced to take to my bed, this time for four
days.
My third experiment was made with Peyote beans, whose properties
are extolled by the American Indians. After eating these beans, the
red men, who use them in the mysteries of their worship, suffer, I
have been informed, from an excruciating nausea, the duration of
which is prolonged. After the nausea has passed its course, a series
of visions is vouchsafed the experimenter, these visions extending in
a series, on various planes, to the mystic number of seven. Under
the spell of these visions, the adepts vaticinate future events. I have
wondered sometimes if it were not possible that the ancient
Egyptians were familiar with the properties of these beans, that
William Blake was under their influence when he drew his mystic
plates.
Be that as it may, I swallowed one bean, which I had been informed
would be sufficient to give me the desired effect, and without interval,
I was carried at once on to the plane of the visions, which
concentrated themselves into one gigantic phantasm. Have you ever
seen Jacques Callot's copperplate engraving of The Temptation of
Saint Anthony? The hideous collection of teratological monsters,
half-insect, half-microbe, of gigantic size, exposed in that picture,
swarmed about me, menacing me with their horrid beaks, their
talons and claws, their evil antennæ. Further cohorts of malignant
monstrosities without bones lounged about the room and sprawled
against my body, rubbing their flabby, slimy, oozing folds against my
legs. After a few more stercoraceous manœuvres, some of which I
should hesitate to describe, even to you, the monsters began to
breathe forth liquid fire, and the pain resulting from the touch of
these tongues of flame finally awoke me. I was violently ill, and my
illness developed in the seven stages traditionally allotted to the
visions. First, extreme nausea, which lasted for two days, second, a
raging fever, third, a procession of green eruptions on my legs,
fourth, terrific pains in the region of my abdomen, fifth, dizziness,
sixth, inability to command any of my muscles, and seventh, a
prolonged period of sleep, which lasted for forty-eight hours.
Nevertheless, I came nearer to success in this experiment than in
any other.
My fourth experiment was made with cocaine, which I procured from
a little Italian boy, about eleven years old, who was acting in a
Bowery barroom as agent for his father. Laying the white crystals on
the blade of an ivory paper-cutter, I sniffed as I had observed the
snow-birds themselves sniff. Immediately, my mind became clear to
an extent that it had never been clear before. My intellect became as
sharp as a knife, as keen as the slash of a whip, as vibrant as an E
string. I seemed to have a power of understanding which I had never
before approached, not only of understanding but also of hearing, for
I caught the conversation of men talking in an ordinary tone of voice
out in the Square. Also, I became abnormally active, nervous, and
intense. I rushed from the room, without reason or purpose, with a
kind of energy which seemed deathless, so strong was its power.
When, however, I endeavoured to make notes, for my mind seethed
with ideas, I was unable to do so. I scratched some characters on
paper, to be sure, but I found them wholly undecipherable the next
day. They were not in English or in any language known to me.
Finally, I ran out of the house and, encountering, on Second Avenue,
a fancy woman of the Jewish persuasion, I accompanied her to her
cubicle, and permitted her to be the subsidiary hierophant in the
mystic rites I then performed. That, concluded Peter, with a
somewhat sorry smile, was the last of my experiments with drugs.
This story and, indeed, this whole phase, amused me enormously.
An ambition which had persuaded its possessor that in order to
become the American Arthur Machen, he must first become an
adept in demonology seemed to me to be the culmination of Peter's
fantastic life, which, indeed, it was. But I said little. As usual, I let him
talk and I listened. There seemed, however, to be a period here and I
took occasion to look over the books, asking him first if he had any
objection to my copying off some of the titles, as I felt that it might be
possible that some day I should want to make some research in this
esoteric realm. He bade me do what I liked and, advancing towards
the book-shelves with the small note-book which I carried with me at
that period in order to set down fleeting thoughts as they came, I
transferred some of the titles therein.
I stopped at last, not from lack of patience on my part, but from
observing the impatience of Peter, who obviously had a good deal
more to say. On my turning, indeed, he began at once.
I have made, he said, some tentative minor experiments but my final
experiments are yet to be attempted. Nevertheless, I have found a
spring-board from which to leap into my romance. Let me read you a
few pages of Arthur Waite's somewhat ironic summary of Dr.
Bataille's Le Diable au XIXe Siècle. Naturally I shall treat the subject
more seriously, but what atmosphere, what a gorgeous milieu in
which to plunge the reader when he shall open my book!
Peter now took from the shelves a small black volume, lettered in
red, and turned over the leaves. First, he said, I shall read you some
of the Doctor's experiences in Pondicherry, and he began:
Through the greenery of a garden, the gloom of a well, and the
entanglement of certain stairways, they entered a great dismantled
temple, devoted to the service of Brahma, under the unimpressive
diminutive of Lucif. The infernal sanctuary had a statue of Baphomet,
identical with that in Ceylon, and the ill-ventilated place reeked with a
horrible putrescence. Its noisome condition was mainly owing to the
presence of various fakirs, who, though still alive, were in advanced
stages of putrefaction. Most people are supposed to go easily and
pleasantly to the devil, but these elected to do so by way of a
charnel-house asceticism, and an elaborate system of self-torture.
Some were suspended from the ceiling by a rope tied to their arms,
some embedded in plaster, some stiffened in a circle, some
permanently distorted into the shape of the letter S; some were head
downwards, some in a cruciform position. A native Grand Master
explained that they had postured for years in this manner, and one of
them for a quarter of a century.
Fr ⡐⡀John Campbell proceeded to harangue the assembly in
Ourdou-zaban, but the doctor comprehended completely, and
reports the substance of his speech, which was violently anti-
Catholic in its nature, and especially directed against missionaries.
This finished, they proceeded to the evocation of Baal-Zeboub, at
first by the Conjuration of the Four, but no fiend appeared. The
operation was repeated ineffectually a second time, and John
Campbell determined upon the Grand Rite, which began by each
person spinning on his own axis, and in this manner
circumambulating the temple, in procession. Whenever they passed
an embedded fakir, they obtained an incantation from his lips, but
still Baal-Zeboub failed. Thereupon, the native Grand Master
suggested that the evocation should be performed by the holiest of
all fakirs, who was produced from a cupboard more fetid than the
temple itself, and proved to be in the following condition:—(a) face
eaten by rats; (b) one bleeding eye hanging down by his mouth; (c)
legs covered with gangrene, ulcers, and rottenness; (d) expression
peaceful and happy.
Entreated to call on Baal-Zeboub, each time he opened his mouth
his eye fell into it; however, he continued the invocation, but no Baal-
Zeboub manifested. A tripod of burning coals was next obtained, and
a woman, summoned for this purpose, plunged her arm into the
flames, inhaling with great delight the odour of her roasting flesh.
Result, nil. Then a white goat was produced, placed upon the altar of
Baphomet, set alight, hideously tortured, cut open, and its entrails
torn out by the native Grand Master, who spread them on the steps,
uttering abominable blasphemies against Adonaï. This having also
failed, great stones were raised from the floor, a nameless stench
ascended, and a large consignment of living fakirs, eaten to the bone
by worms and falling to pieces in every direction, were dragged out
from among a number of skeletons, while serpents, giant spiders,
and toads swarmed from all parts. The Grand Master seized one of
the fakirs and cut his throat upon the altar, chanting the satanic
liturgy amidst imprecations, curses, a chaos of voices, and the last
agonies of the goat. The blood spirted forth upon the assistants, and
the Grand Master sprinkled the Baphomet. A final howl of invocation
resulted in complete failure, whereupon it was decided that Baal-
Zeboub had business elsewhere. The doctor departed from the
ceremony and kept his bed for eight-and-forty hours.
Peter looked up from the book in his hand with an expression of
ironic exultation which was very quaint.
What do you think of that? he asked.
Very pretty, I ventured.
Very strong for the beginning of my romance! he cried. You see, I
shall commence with this failure and work up gradually to the final
brilliant success. Let me introduce you to another passage from
Waite's summary of Dr. Bataille's masterpiece: He turned a few more
leaves and presently was reading again:
A select company of initiates proceeded in hired carriages through
the desolation of Dappah, under the convoy of the initiated
coachmen, for the operation of a great satanic solemnity. At an easy
distance from the city is the Sheol of the native Indians, and hard by
the latter place there is a mountain 500 feet high and 2000 long on
the summit of which seven temples are erected, communicating one
with another by subterranean passages in the rock. The total
absence of pagodas makes it evident that these temples are devoted
to the worship of Satan; they form a gigantic triangle superposed on
the vast plateau, at the base of which the party descended from their
conveyances, and were met by a native with an accommodating
knowledge of French. Upon exchanging the Sign of Lucifer, he
conducted them to a hole in the rock, which gave upon a narrow
passage guarded by a line of Sikhs with drawn swords, prepared to
massacre anybody, and leading to the vestibule of the first temple,
which was filled with a miscellaneous concourse of Adepts. In the
first temple, which was provided with the inevitable statue of
Baphomet, but was withal bare and meagrely illuminated, the doctor
was destined to pass through his promised ordeal for which he was
stripped to the skin, and placed in the centre of the assembly, and at
a given signal one thousand odd venomous cobra de capellos were
produced from holes in the wall and encouraged to fold him in their
embraces, while the music of flute-playing fakirs alone intervened to
prevent his instant death. He passed through this trying encounter
with a valour which amazed himself, persisted in prolonging the
ceremony, and otherwise proved himself a man of such
extraordinary metal that he earned universal respect. From the
Sanctuary of the Serpents, the company then proceeded into the
second temple or the Sanctuary of the Phœnix.
The second temple was brilliantly illuminated and ablaze with
millions of precious stones wrested by the wicked English from
innumerable conquered Rajahs; it had garlands of diamonds,
festoons of rubies, vast images of solid silver, and a gigantic Phœnix
in red gold more solid than the silver. There was an altar beneath the
Phœnix, and a male and female ape were composed on the altar
steps, while the Grand Master proceeded to the celebration of a
black mass, which was followed by an amazing marriage of the two
engaging animals, and the sacrifice of a lamb brought alive into the
temple, bleating piteously, with nails driven through its feet.
The third temple was consecrated to the Mother of fallen women,
who, in memory of the adventure of the apple, has a place in the
calendar of Lucifer; the proceedings consisted of a dialogue between
the Grand Master and the Vestal.
The fourth temple was a Rosicrucian Sanctuary, having an open
sepulchre, from which blue flames continually emanated; there was
a platform in the midst of the temple designed for the
accommodation of more Indian Vestals, one of whom it was
proposed should evaporate into thin air, after which a fakir would be
transformed before the company into a living mummy and be
interred for a space of three years. The fakir introduced his
performance by suspension in mid-air.
The fifth temple was consecrated to the Pelican.
The sixth temple was that of the Future and was devoted to
divinations, the oracles being given by a Vestal in a hypnotic
condition, seated over a burning brazier.
The assembly now thoughtfully repaired to the seventh temple,
which, being sacred to Fire, was equipped with a vast central
furnace surmounted by a chimney and containing a gigantic statue of
Baphomet; in spite of the intolerable heat pervading the entire
chamber, this idol contrived to preserve its outlines and to glow
without pulverizing. A ceremony of an impressive nature occurred in
this apartment; a wild cat, which strayed in through the open window,
was regarded as the appearance of a soul in transmigration, and in
spite of its piteous protests, was passed through the fire to Baal.
And now the crowning function, the Magnum Opus of the mystery,
must take place in the Sheol of Dappah; a long procession filed from
the mountain temples to the charnel-house of the open plain; the
night was dark, the moon had vanished in dismay, black clouds
scudded across the heavens, a feverish rain fell slowly at intervals,
and the ground was dimly lighted by the phosphorescence of the
general putrefaction. The Adepts stumbled over dead bodies,
disturbing rats and vultures, and proceeded to the formation of the
magic chain, sitting in a vast circle, every Adept embracing his
particular corpse.
Well? asked Peter, closing the book. Well?
Kolossal! I shouted, in German.
Isn't it, and there's ever so much more, wonderful stories,
incantations and evocations in the works of Arthur Waite, Moncure
Daniel Conway, Alfred Maury, J. Collin de Plancy, François
Lenormant, Alphonse Gallais, the Abbé de Montfaucon de Villars,
J.G. Bourgeat, and William Godwin. Have you ever heard of The
Black Pullet or The Queen of The Hairy Flies?
This time, Carl; he spoke with great intensity and earnestness, I am
on the right track. I am convinced that to give a work of this character
a proper background one must know a great deal more than one
tells. That, in fact, is the secret of all fine literature, the secret of all
great art, that it conceals and suggests. The edges, of course, are
rounded: it is not a rough and obvious concealment. You cannot
begin not to tell until you know more than you are willing to impart.
These books have given me a good deal, but I must go farther—as I
am convinced that Machen has gone farther. I am going through with
it ... all through with it, searching out the secrets of life and death, a
few of which I have discovered already, but I have yet to make the
great test. And when I know what I shall find out, I shall begin to
write ... but I shall tell nothing.
Peter was flaming with enthusiasm again. It wasn't necessary for me
to speak. He required an audience, not an interlocutor.
Why not now? he demanded suddenly. Why not now and here, with
you?
What do you mean? I queried.
Why not make the great experiment now? I am prepared and the
moon and the planets are favourable. Are you willing to go through
with it? I must warn you that you will never be the same again. You
may even lose your life.
What will happen? I asked.
The earth will rock. A storm will probably follow, thunder and
lightning, balls of fire, thunderbolts, showers of feathers, and then we
shall dissolve into ... into a putrid mass, the agamous mass from
which we originated, neither male nor female, with only a glowing
eye, a great eye, radiating intelligence out of its midst. Then Astaroth
himself (I shall call Astaroth, because his inferiors in the descending
hierarchy, Sargatanas and Nebiros, dwell in America) will appear, in
one of his forms, perhaps refulgent and beautiful, perhaps ugly and
tortured and hideously deformed, perhaps black or yellow or blue,
but assuredly not white or green. He may be entirely covered with
hair or entirely covered with eyes, or he may be eyeless. Mayhap, he
will be lean and proud and sad, and he will probably limp, for you
know he is lame. His feet will be cloven, he will wear a goat's beard,
and you may distinguish him further by the cock's feather and the
ox's tail. Or, perhaps, he may arrive in the shape of some monster:
the fierce flying hydra called the Ouranabad, the Rakshe who eats
dragons and snakes, the Soham, with the body of a scarlet griffin
and the head of a four-eyed horse, the Syl, a basilisk with a human
face.... But, however he may appear, in his presence you shall learn
the last secrets of all the worlds.
And then what will happen?
Then I shall speak the magic formula and we will resume our proper
shapes but from that moment on we shall hover—literally, not
pathologically—between life and death. We shall know everything. ...
and eventually we shall pay the price....
Like Faust?
Like Faust ... that is, if we are not clever enough to outwit the demon.
Those who practise devilments usually find some means to
circumvent the devil.
I appeared to ponder.
I am willing to go through with it, I said at last.
Good! I knew you would be. Let's get to work at once!
He lifted the most ponderous volume in the laboratory from the floor
to the top of an old walnut refectory table. The book was bound in
musty yellow vellum, clasped with iron, and the foxed leaves were
fashioned from parchment made from the skin of virgin camels. As
he opened it, I saw that the pages were inscribed with cabalistic
characters and symbols, illuminated in colours, none of which I could
decipher. Lou Matagot jumped on to the table and sat on the leaves
at the top of the book, forming a paper weight. He sat with his back
to Peter and his long, black tail played nervously up and down the
centre of the volume.
Peter now drew a circle with a radius of twelve or thirteen feet
around us, inscribing within its circumference certain characters and
pentacles. Then he plunged a dagger through what I recognized to
be a sacred wafer, which he told me had been stolen from a church
at midnight, at the same time, muttering what, from the tone of his
voice, I took to be blasphemous imprecations, although the language
he used was unfamiliar to me. Next he arranged a copper chafing-
dish over a blue flame and began to stir the ingredients, esoteric
powders and crystals of bright colours. Now he lovingly lifted a
crystal viol, filled with a purple liquid, and poured the contents into a
porcelain bowl. Instantly, there was a faint detonation and a thick
cloud of violet vapour mounted spirally to the ceiling. All the time,
occasionally referring to the grimoire on the table, and employing
certain unmentionable symbolic objects in the manner prescribed, he
muttered incantations in the unknown tongue. The room swam with
odours and mists, violet clouds and opopanax fogs. So far, the
invocation was pretty and amusing but it resembled the arcane rites
of Paul Iribe more than those of Hermes Trismegistus.
Now Peter pulled three black hairs from the cat's tail, which Lou
Matagot delivered with a yowl of rage, springing at the same time
from the table to the top of the cabinet, whence he regarded us
through the mists and vapours, with his evil yellow eyes. The hairs
went into the chafing-dish and a new aroma filled the room. The
claws of an owl, the flower of the moly, and the powder of vipers
followed and then Peter opened a long flat box which nearly covered
one end of the huge table, and a nest of serpents, with bellies of rich
turquoise blue and backs of tawny yellow, marked with black
zigzags, reared their wicked heads. He called them by name and
they responded by waving their heads rhythmically. I began to grow
alarmed and dizzy. Vade retro, Satanas! was on tip of my tongue.
For a few seconds, I think, I must have fainted. When I revived, I still
heard the chanting of the incantation and the sound of tinkling bells.
The serpents' heads still waved in rhythm and their bodies, yellow
and turquoise blue, were elongated in the air until they appeared to
be balancing on the tips of their tails. The eyes of Lou Matagot
glared maliciously through the thick vapours and the cat howled with
rage or terror.
Now! cried Peter, for the first time in English. Now!
My nails dug holes in the palms of my perspiring hands. Peter
renewed his nocuous muttering and casting the wafer, transfixed by
the dagger, into the porcelain bowl containing the violet fluid, he
poured the whole mixture into the copper chafing-dish.
There was a terrific explosion.

FOOTNOTES:
[3] A feeling in which he encourages belief in his preface to a new
edition of "The Great God Pan"; 1916.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like