100% found this document useful (7 votes)
71 views85 pages

Full Download Java Programming Exercises Volume Two Java Standard Library 1st Edition Christian Ullenboom PDF DOCX

Programming

Uploaded by

kamnomapou
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (7 votes)
71 views85 pages

Full Download Java Programming Exercises Volume Two Java Standard Library 1st Edition Christian Ullenboom PDF DOCX

Programming

Uploaded by

kamnomapou
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

Download the full version of the ebook at ebookfinal.

com

Java Programming Exercises Volume Two Java


Standard Library 1st Edition Christian Ullenboom

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

OR CLICK BUTTON

DOWNLOAD EBOOK

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


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

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/

ebookfinal.com

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/

ebookfinal.com

Java Servlet Programming Second Edition Jason Hunter

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

ebookfinal.com

Wireless Java Programming with J2ME 1st Edition Yu Feng

https://ebookfinal.com/download/wireless-java-programming-
with-j2me-1st-edition-yu-feng/

ebookfinal.com
Java Programming 24 Hour Trainer 1st Edition Yakov Fain

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

ebookfinal.com

Object Oriented Programming using Java 1st edition Edition


Kendal S.

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

ebookfinal.com

Object Oriented Programming and Java Second Edition Danny


Poo

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

ebookfinal.com

Introduction to Java Programming Comprehensive Version 6th


Edition Liang

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

ebookfinal.com

Elements of Programming Interviews in Java 2nd Edition


Adnan Aziz

https://ebookfinal.com/download/elements-of-programming-interviews-in-
java-2nd-edition-adnan-aziz/

ebookfinal.com
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" );
26 Java Programming Exercises

double y = scanner.nextDouble();
svg.append( x ).append( "," ).append( y ).append( " " );
}

svg.append( "\" style=\"fill:lime;stroke:purple;stroke‑width:1\" />\n</svg>" );


System.out.println( svg );
}

The file consists of sequences of integers separated by either a semicolon or a newline, generally speaking
by arbitrary white space. We need to find a tokenizer that we can feed with a regular expression that stands
for just these separators. Since we want to read from a file and process that with regular expressions, the
class Scanner is a good choice. This is also how the proposed solution does it.
The Scanner is connected to an input stream, the file we would like to read. The character encoding
is explicitly set to UTF‑8.
Then the Scanner is initialized with a regular expression for the delimiters. These delimiters are
set by the Scanner method useDelimiter(…). It is important to set the Locale.ENGLISH because
by default the Scanner is preconfigured with the Locale by the operating system, and if that is, for
example, German, the Scanner expects floating‑point numbers with a comma as separator. But the
source always has English formatted numbers.
After the Scanner is prepared, the program can produce the output. It starts with the SVG container
and the polygon start tag. The Scanner method hasNext() helps to iterate through the file. When the
hasNext() method returns a token, we always expect pairs. We can read the first integer, and now there
must be a second integer. But if the Scanner cannot give a new token, this is an error, and we raise an
exception. If the second number exists, it will also be read in. The pair can then be placed in the SVG
container.
At the end of the loop, we close the polygon tag and print the SVG element to the screen. For the
output, we don’t need to pay attention to the language for append(double) because the formatting of
the double is automatically in English.

Compress Strings Lossless by Runlength Encoding


com/tutego/exercise/string/SimpleStringCompressor.java

public static String compress( String string ) {

if ( string.isEmpty() )

return "";

char lastChar = string.charAt( 0 );


int count = 1;
StringBuilder result = new StringBuilder( string.length() );

for ( int i = 1; i < string.length(); i++ ) {


char currentChar = string.charAt( i );
if ( currentChar == lastChar )
count++;
else {
result.append( lastChar );
if ( count > 1 )
result.append( count );
count = 1;
1 • Advanced String Processing 27

lastChar = currentChar;
}
}

result.append( lastChar );
if ( count > 1 )
result.append( count );

return result.toString();
}

private static CharSequence decodeToken( String token ) {

if ( token.isEmpty() )
return "";

if ( token.length() == 1 )
return token;

int length = Integer.parseInt( token.substring( 1 ) );


return String.valueOf( token.charAt( 0 ) ).repeat( Math.max( 0, length ) );
}

public static String decompress( String string ) {


StringBuilder result = new StringBuilder( string.length() * 2 );
Matcher pattern = Pattern.compile( "[.‑](\\d*)" ).matcher( string );

while ( pattern.find() )
result.append( decodeToken( pattern.group() ) );

return result.toString();
}

In the first step, we want to compress the string. To achieve this, we first query whether the string contains
any text at all; if not, we are quickly done with the task.
To see how many of the same characters occur in the text in a row, we use a variable lastChar for
the last character seen so that we can compare a new character with the last character. In addition, we
note the number of same characters in count. Since this result is freshly built, we add a variable result
of the data type StringBuilder.
The for loop goes over each character and stores it in the auxiliary variable currentChar. Now,
two things can happen: The character currentChar just read can be the same as the previous character
in lastChar, or it can be a different character. We have to handle this difference.
The initial check determines if the previously observed character matches the currently read char‑
acter. If it’s a match, we simply increase the counter and continue the loop. However, if the newly read
character differs from the previous one, the local compression process concludes. We begin by writing
this character to the buffer. Then, we address the count: if more than one identical character was previ‑
ously counted, we input that count into the data stream. But if there was just one character, we don’t add
1 to the buffer, in accordance with the task’s instructions. After finalizing the character‑counter pair, it’s
essential to reset the counter to 1. We are almost done with the loop. The moment a new character is found,
we set lastChar to exactly the current character currentChar.
When we are done with the loop, we still have a character in lastChar and count. We therefore
perform the same query as before in the case distinction, and append the counter to the string if the coun‑
ter is greater than 1.
28 Java Programming Exercises

In the method for unpacking, we fall back on the pattern that results from the compression. There
are always pairs of a string and a number, with the special case that the pair is single, and the number
is missing. Using a regular expression, we run the entire string and look at all the pairs. To keep the
method from getting too big, we use a helper method called decodeToken(String) that takes a pair
and expands it.
First, the method must find out whether the token consists of only one character or of several charac‑
ters. If the string consists of only one character, then it must have been our symbol, and it comes into the
output. If the string is longer than 1, then there is a length encoding from the second position upward. With
substring(1) we extract the string and convert it to an integer, so that the repeat(int) method of
String can generate us exactly this number of characters token.charAt(0). With substring(1)
we extract the string and convert it to an integer, so that the repeat(int) method of String can gener‑
ate us exactly this number of characters token.charAt(0).

Quiz: Encoding for Unicode Characters


When we write a string in source code, we don’t worry much about encoding because we can write numer‑
ous characters directly in quotes. But when these strings are written to a file, for example, the encoding is
relevant because other parties will naturally want to read that file again.
Unicode’s characters require four bytes in their full extent. However, this is a waste if the character
can only be encoded in one byte, such as a simple ASCII character. Therefore, one encodes Unicode char‑
acters to get the shortest possible representation. Common encodings are UTF‑8 and UTF‑16; they can
represent all Unicode characters. This is not true for Latin‑1, for example, because Latin‑1 is only eight
bytes, and hundreds of thousands of characters cannot be represented in Latin‑1. UTF‑8 encoding will use
one byte if possible, then use two bytes if possible, otherwise use three or four.

Quiz: Order of Strings with and without Collator


The outputs are:
com/tutego/exercise/string/CollatorDemo.java

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


System.out.println( comparator.compare( "a", "ä" ) ); // < 0
System.out.println( comparator.compare( "ä", "z" ) ); // > 0 !!
System.out.println( comparator.compare( "n", "ñ" ) ); // < 0
System.out.println( comparator.compare( "ñ", "o" ) ); // > 0 !!

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


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

TABLE 1.3 Bit assignments of UTF8 encoding


NUMBER OF FIRST CODE LAST CODE
BYTES BITS POINT POINT BYTE 1 BYTE 2 BYTE 3 BYTE 4
1 7 U+0000 U+007F 0*******
2 11 U+0080 U+07FF 110***** 10******
3 16 U+0800 U+FFFF 1110**** 10****** 10******
1 • Advanced String Processing 29

TABLE 1.4 Some characters with their positions in the Unicode standard
CHARACTER θ A a Ä ß ä ñ
Code point (decimal) 48 65 97 196 223 228 241

The natural ordering of strings is lexicographic, meaning that the position of the character in the Unicode
alphabet counts. Let’s illustrate this with some characters.
From the table, you can see that the digits are first, followed by the uppercase letters and then the
lowercase letters. The umlauts are far behind the capital letters and not sorted between the upper and
lower case letters.
Umlauts are regular letters in German, which do not come after “Z” in the order. The standard DIN
5007‑1 describes under “Ordering of character sequences (ABC rules)” two sorting procedures:
DIN 5007, variant 1 (used for words, for example, in dictionaries)

• “ä” and “a” are the same.


• “ö” and “o” are the same.
• “ü” and “u” are the same.
• “ß” and “ss” are the same,

DIN 5007, variant 2 (special sorting for lists of names, such as in telephone directories)

• “ä” and “ae” are the same.


• “ö” and “oe” are the same.
• “ü” and “ue” are the same.
• “ß” and “ss” are the same.

There are similar rules for other languages. The lexicographical order does not support this. Therefore,
the Unicode Collation Algorithm describes how the sorting looks like in different national languages. For
an introduction, see also https://en.wikipedia.org/wiki/Unicode_collation_algorithm.
In Java Collator objects are available. They are initialized with a Locale object. In addition
to the language, so‑called levels can be passed; the Javadoc gives further examples under the heading
“Collator strength value”.
Mathematics
2
Integers and floating‑point numbers already appeared in the first exercises; we were using the common
mathematical operators to crunch numbers. But Java does not have an operator for everything, and so
the class Math offers further methods and constants; early on we used Math.random(), for example.
Throughout this chapter’s upcoming tasks, our focus will be on various rounding techniques, particularly
exploring the methods offered by the Math class. In addition, the java.math package provides two
classes that can be used to represent arbitrarily large numbers—there are tasks for these as well.
Prerequisites

• Know rounding methods of the class Math.


• Know BigInteger and BigDecimal.

Data types used in this chapter:

• java.lang.Math
• java.math.BigInteger
• java.math.BigDecimal

THE CLASS MATH


The class Math contains numerous mathematical functions. It is also important to look at wrapper classes,
for example, or at the Scanner or Formatter when it comes to converting a number to a string or pars‑
ing a string so that there is a primitive type at the end again.

Quiz: Rule of Thumb ⭑


There are different approaches and different kinds of problems for rounding numerical values:

• On the one hand, a floating‑point number can be converted to an integer.


• On the other hand, the number of decimal places can be reduced for a floating‑point number.

The Java library supports different possibilities for conversion and rounding, among other things with

• The explicit type conversion (int) double → int.


• Math.floor(double) → double.
• Math.ceil(double) → double.
• Math.round(double) → long.

30 DOI: 10.1201/9781003495550-3


2 • Mathematics 31

• Math.rint(double) → double.
• BigDecimal and setScale(..) → BigDecimal.
• NumberFormat, configured with setMaximumFractionDigits(…), then format(…)
→ String.
• DecimalFormat, configured with setRoundingMode(…), then format(…) → String.
• Formatter with a format string, then format(…) → String.

Four of the methods originate from Math, but when it comes to gigantic and precise floating‑point num‑
bers or string representation, other classes are involved. Since the methods differ slightly in the result, the
following task should make these differences clear once again.
Task:

• Fill in the following table with the results of the roundings:

DOUBLE (INT) (INT) (INT)


VALUE D (INT) D FLOOR(D) CEIL(D) ROUND(D) RINT(D)

-2.5
-1.9
-1.6
-1.5
-1.1
1.1
1.5
1.6
1.9
2.5

Check If Tin Tin Cheated on Rounding ⭑


The accountant Tin Tin does the accounting for Captain CiaoCiao of income and expenses. She gets posi‑
tive and negative floating‑point values and writes down the total as a rounded integer for a summary at
the end. Captain CiaoCiao suspects that Tin Tin is not being completely honest and is pocketing the penny
amounts when she should use commercially rounding. As a reminder, if the number at the first omitted
decimal place is a 0, 1, 2, 3, or 4, round down; if it is 5, 6, 7, 8, or 9, round up.
To test his guess, Captain CiaoCiao needs a program that can sum and check different rounding
modes.
Task:

• Given an array of floating‑point numbers (positive and negative) and the sum converted to an
integer by Tin Tin.
• Captain CiaoCiao wants to find out which rounding was used to form the integer of the sum.
Therefore, the elements in the array are to be summed and compared to Tin Tin’s sum. The
rounding is done after the numbers are added.
• Implement a method RoundingMode detectRoundingMode(double[] numbers,
int sum) that gets a double array of numbers and the sum of Tin Tin and checks which
rounding mode was used.
• To allow the rounding mode to be represented, introduce an enumeration type:
enum RoundingMode {
CAST, ROUND, FLOOR, CEIL, RINT, UNKNOWN;
}
32 Java Programming Exercises

• The enumeration elements represent different rounding modes:


• (int), that is, a type conversion.
• (int) Math.floor(double).
• (int) Math.ceil(double).
• (int) Math.rint(double).
• (int) Math.round(double).

• Which rounding is bad for Captain CiaoCiao and good for Tin Tin? Which variation could Tin
Tin use to cheat?

Example:

• The call might look like this:


double[] numbers = { 199.99 };
System.out.println( detectRoundingMode( numbers, 200 ) );

Notes:

• There is an enumeration type RoundingMode in the java.math package, but for our case,
it does not fit the task.
• It may well happen that more than one rounding mode fits—such as when the sum of the
­floating‑point values itself gives an integer—then the method is free to choose one of the round‑
ing modes.

HUGE AND VERY PRECISE NUMBERS


The classes java.math.BigInteger and java.math.BigDecimal can be used to represent arbi‑
trarily large integer and floating‑point numbers.

Calculate Arithmetic Mean of a Large Integer ⭑


To calculate the arithmetic mean of two numbers, they are added together and divided by two. This works
well if the sum of the two values does not exceed the largest number that can be represented. If there is
an overflow, the result is wrong. Some algorithms in computer science can handle this problem as well,
but we can make it a little easier and take the higher data type in each case. For example, if we want to
calculate the mean value of two int variables, we convert the two int to a long, add the numbers,
divide, and convert back to the int. With the long data type, there is no larger primitive data type, but
the BigInteger type can be used well for the case.
Task:

• Calculate the arithmetic mean of two long values so that there is no overflow and wrong
results. The result should be a long again.
2 • Mathematics 33

Number by Number over the Phone ⭑


A new deal has made Bonny Brain a lot of money. The number is so big that you can’t just announce it
over the phone at all; it has to be conveyed in chunks.

Task:

• Write a new method BigInteger completeNumber(int... parts) that gets a vari‑


able number of numbers and returns the big total number at the end.

Example:

• completeNumber(123, 22, 989, 77, 9) returns a BigInteger with the value


12322989779.
34 Java Programming Exercises

Develop Class for Fractions and Truncate Fractions ⭑⭑


Bonny Brain is trying a new recipe for a rum punch. Fractions like “1/4 liter grape juice” or “1/2 liter rum”
keep appearing in the directions for making it. For the party, she prepares 100 servings, and fractions like
“100/4 liters” occur. The fractions can be shortened so that Bonny Brain knows, for example, that 25 liters
of grape juice must be purchased.
Task:

1. Create a new class Fraction.


2. Let there be a constructor Fraction(int numerator, int denominator) that stores
numerator and denominator in public final variables.
• Consider whether there can be faulty arguments, which we should report through exceptions.
• Every created fraction should be simplified automatically. Use the gcd(…) method of
BigInteger, which calculates the greatest common divisor (gcd)_. Remember: the gcd
of numerator and denominator is the largest number by which both are divisible. You can
simplify the fraction by dividing both the numerator and denominator by this number.
• Both numerator and denominator can be negative, but then you can flip the sign so that both
values become positive.
• The objects are all supposed to be immutable, and therefore the variables can be public
since they are not supposed to be changed after initialization via the constructor. In other
words, the class Fraction does not contain any setters.
3. Add the constructor Fraction(int value), where the denominator automatically becomes 1.
4. Implement a method to multiply fractions and detect overflows.
5. Implement a method reciprocal() that returns the inverse of a fraction, that is, swaps
the numerator and denominator. Thanks to this method, the division of fractions can be
implemented.
6. Fraction shall extend java.lang.Number and implement all mandatory methods.
7. Fraction shall implement Comparable because fractions can be converted to a decimal
number, and decimal numbers have a natural order.
8. Fraction shall implement equals(…) and hashCode() correctly.
9. Implement a toString() method that returns a string as bare as possible.
2 • Mathematics 35

T
«interface»
Number
Comparable

«final»
Fraction

+numerator: int «final»


+denominator: int «final»
Operationen
+Fraction(numerator: int, denominator: int)
+Fraction(value: int)
+reciprocal(): Fraction
+multiply(other: Fraction): Fraction
Number
+intValue(): int
+longValue(): long
+doubleValue(): double
+floatValue(): float
Comparable
+compareTo(other: Fraction): int
Object
+equals(other: Object): boolean
+hashCode(): int
+toString(): String

FIGURE 2.1 UML diagram of Fraction.

SUGGESTED SOLUTIONS

Quiz: Rule of Thumb


TABLE 2.1 Different roundings of a floating‑point number d in comparison
(INT) (INT) (INT)
VALUE d (INT) d FLOOR(d) CEILING(d) ROUND(d) RINT(d)
‑2.5 ‑2 ‑3 ‑2 ‑2 ‑2
‑1.9 ‑1 ‑2 ‑1 ‑2 ‑2
‑1.6 ‑1 ‑2 ‑1 ‑2 ‑2
‑1.5 ‑1 ‑2 ‑1 ‑1 ‑2
‑1.1 ‑1 ‑2 ‑1 ‑1 ‑1
1.1 1 1 2 1 1
1.5 1 1 2 2 2
1.6 1 1 2 2 2
1.9 1 1 2 2 2
2.5 2 2 3 3 2
Other documents randomly have
different content
1076 William refused to pay homage to the see of Rome for the possession of
England, and forbade his bishops to attend the council that Gregory had
summoned. He however sent to Rome the tribute of Peter-pence. A great
earthquake in England, and a frost from November to the end of April.
1078 William laid the foundation of London.
1079 The Norman laws and language introduced.
1085 Thirty-six parishes, containing a circuit of sixty miles in Hampshire, were
depopulated and destroyed without any compensation to the inhabitants,
in order to make New-Forest for William’s diversion of hunting. The
tyrannical laws of the Forest were made.
1087 A dreadful famine in England. William went to France and destroyed the
country with fire and sword. He died at Rouen by a fall from his horse,
and was buried at Caen, in Normandy, in the monastery he had himself
founded, but was denied interment by the proprietor till the fees were
paid.
1088 An earthquake in London. A great scarcity this year, and corn not ripe till
the end of November. William II embarked for Normandy, and made war
against his brother Robert. William returned to England; and Henry his
brother, was forced to wander without a residence.
1091 A tempest which destroyed 500 houses. Great part of London consumed by
fire.
1092 Malcolm, king of Scotland, killed at Alnwick, by the Earl of Northumberland.
1094 Man and beast destroyed by a great mortality.
1095 Peter the hermit preached up a crusade to the Holy Land.
1096 The Christian princes raised 700,000 men, and began the holy war. The first
single combat for deciding disputes between the nobility.
1097 The Voyage for the Holy War, was first undertaken. Being a contrivance of
Pope Urban, to compose the divisions of the church, the whole Christian
world being then at discord among themselves. This war lasted almost
three hundred years.
1098 Tower surrounded with a wall. Westminster Hall built. Its dimensions are
224 feet by 74.
1099 Jerusalem taken by storm, and forty thousand Saracens put to the sword.
1100 Godwin-Sands, the property of Earl Godwin, first overflowed by the sea,
destroying four thousand acres of land. King Henry married the lady
Maud, daughter of Margaret, late queen of Scots, and niece to Edgar
Atheling, descended from Edmund Ironside. The use of fire and candle,
after eight o’clock at night restored to the English.
1106 King Henry subdues Normandy, takes Robert prisoner, and orders his eyes
to be put out.
1109 Three shillings levied on every hide of land, which tax produced £824,000.
1110 Arts and sciences taught again at Cambridge.
1112 A plague in London.
1114 The Thames dry for three days.
1116 A council called of the nobility, which is supposed by some to be the first
parliament.
1122 The order of the Knights Templars founded.
1123 The first park (Woodstock) made in England.
1129 The revenue of the royal demesne altered from kind to specie.
1132 London mostly destroyed by fire.
1134 Duke Robert, having been imprisoned and blinded twenty-eight years,
ended his miserable existence. Wheat sufficient to subsist 100 men one
day, sold at one shilling—a sheep 4d.
1136 The distance from Aldgate to St. Paul’s (included), destroyed by fire in
London.
1136 The Empress Maud besieged in Oxford, and made her escape from thence
on foot, being disguised in white, on a snowy night, to Abingdon. The tax
of Danegelt entirely abolished. No less than fifteen hundred strong
castles in the kingdom.
1139 The Empress Matilda lands at Arundel, and claims the crown. Makes her
natural brother, Robert, Earl of Gloucester, her general.
1141 Stephen taken prisoner at the battle of Lincoln, and confined in chains by
Maud, in Gloucester gaol. Stephen released.
1148 A new Crusade undertaken.
1151 Gratian of Bologna, the monk, collects the canon laws after twenty-four
year’s labour.
1153 Agreed, between Henry and Stephen, that eleven hundred of the castles,
erected by permission of the latter, should be abolished. Appeals were
first made to the Pope, and canon laws instituted. There was no regular
mode of taxation. Contending parties supported themselves by
plundering each other’s tenants. There were more abbeys built, than in
the hundred years preceding.
1155 The castles demolished, agreeably to the treaty of 1153.
1157 The Welsh, subdued, do homage, and swear allegiance. A sect, called
Publicans, rejecting baptism and marriage, came into England from
Germany. The bishops pronounced them heretics; they were branded in
the forehead and whipped.
1174 Henry scourged for the supposed murder of Becket. The bishops and
abbots of Scotland swore fealty to England and its church. The earls and
barons of Scotland swore allegiance to Henry and his son.
1176 London bridge begun by Peter Colmar, a priest. It was thirty-three years in
building.
1177 Glass windows in private houses first used. Debasers of coin first severely
punished. A new coinage.
1185 A total eclipse of the sun; and, at the same time, an earthquake, which
destroyed Lincoln and other churches.
1186 Near Oxford in Suffolk, was a sort of wild-man caught in a fisherman’s net.
Trial by jury established, or the verdict of twelve men, to punish
offenders with the loss of a leg or banishment. Henry secreted his
concubine (Rosamond, daughter of Walter, lord Clifford) in a labyrinth at
his palace at Woodstock, who being discovered by his queen Eleanor, was
poisoned by her, and buried at Godstow nunnery near Oxford.
1189 The castles of Berwick and Roxburgh delivered up to William, king of
Scotland, who was, at the same time relieved from subjection to England.
Richard began, with Philip of France, his expedition to the Holy Land.
About this time were those famous robbers and outlaws, Robin Hood,
and Little John. Upon Richard’s coronation-day, (3rd September,) was a
great slaughter of the Jews in London, who coming to offer their presents
to the new king, were set upon by the mob, to the loss of their lives and
estates; and the example of London was followed by other towns, as
Norwich, St. Edmunds-Bury, Lincoln, Stamford and Lynn.
1190 King Richard marries the Lady Berengaria, daughter to the king of Navarre,
and goes to the Holy Land, having sold some of the crown lands to raise
the money for that expedition. In which voyage he took the Island of
Sicily and Cyprus.
1191 Richard obtained a great victory over Saladin, at Jerusalem, September 3.
He soon after defeated a Turkish troop of 10,000, who were guarding a
caravan to Jerusalem. He took, on this occasion, 3,000 loaded camels,
4,000 mules, and an inestimable booty which he gave to his troops.
1192 Multitudes destroyed by a raging fever, which lasted five months. Two suns
appeared on Whitsunday, so resembling each other, that astronomers
could scarcely distinguish which was the centre of our system, according
to Copernicus.
1194 Richard having been absent four years, returned to England, March 20. He
made war with France, and having obtained a great victory over the
French at Gysors “Not we” says he, “but Dieu et mon Droit,” i.e. God and
my Right, has obtained this victory. Ever since, the kings of England have
made it their motto. The king of Scotland carried the sword of state at
the second coronation of Richard.
1197 Robin Hood, being indisposed, and desiring to be blooded, was purposely
and treacherously bled to death. In this reign, companies and societies
were first established in London. Three lions passant first borne in the
king’s shield.
1199 Surnames first used.
1200 The king of Scotland performed public homage to John, at the parliament
held in Lincoln. Assize of bread first appointed.
1204 The Inquisition established by Pope Innocent III. The most ancient writ of
parliament directed to the bishop of Salisbury. Five moons seen at one
time in Yorkshire.
1205 A fish resembling a man taken on the coast of Suffolk, and kept alive six
months.
1207 The first annual mayor and common council of London chosen.
1208 Divine service throughout the kingdom suspended by the Pope’s interdict.
1209 John excommunicated.
1210 Twenty Irish princes do homage to John at Dublin. The clergy taxed to the
amount of £100,000.
1211 England absolved by the Pope from its allegiance to John.
1212 Great part of London burnt down by a fire which began in Southwark in
Middlesex, and consumed the Church of St. Mary Overy, went on to the
bridge; and whilst some were quenching the flames, the houses at the
other end took fire, so that numbers were inclosed; many were forced to
leap into the Thames, whilst others, crowding into boats that came to
their relief, were the cause of nearly 3,000 people perishing, partly by
water, and partly by fire.
1213 John resigned his dominions to the Pope, and was absolved. In this reign,
sterling money was first coined.
1216 Wheat was sold for twelve-pence a quarter, and beans and oats for four-
pence a quarter.
1222 The ward-ship of heirs and their lands was granted to king Henry.
1226 The Pope demanded a sum annually from every cathedral church and
monastery in Christendom. This demand was refused. Thomas à Becket’s
bones were enshrined in gold and precious stones. Two imposters
executed, the one for pretending to be the Virgin Mary, the other Mary
Magdalen.
1228 The Jews obliged to pay a third part of their property to the king.
1236 Water first conveyed to London with utility. The Pope’s ambassador going to
Oxford, was set upon by the students, and his brother slain, himself
hardly escaping; whereupon the Pope excommunicated the University,
and made all the bishops who interceded in the University’s behalf, and
the students, go without their gowns, and barefooted from St. Paul’s
church to his house, being about a mile, before he would revoke the
sentence.
1246 Titles first used.
1251 Wales entirely subdued and subjected to English laws.
1253 Fine linen first made in England.
1255 All possessing £15 per annum, obliged to be knighted, or pay a fine.
Tapestry introduced by Eleanor, wife of prince Edward.
1264 There were 700 Jews slain in London, because one of them would have
forced a Christian to have paid more than two-pence, for the use of
twenty shillings a week.
1269 About this time, Roger Bacon, a divine of Merton College in Oxford, was
imprisoned by the Pope, for preaching against the Romish church.
1273 The Scots swear fealty to Edward, June 12.
1275 Jews obliged to wear a badge; usury restrained by the same act of
parliament, October 6.
1279 The first statute of Mortmain. 280 Jews hung for clipping and coining.
1282 The Rolls in Chancery-lane given to the Jews. Wales reduced, after having
preserved her liberties 800 years.
1284 Edward II born at Caernarvon, and created first prince of Wales, April 25.
1285 The abbey Church of Westminster finished, being sixty years in building.
1286 The Jews seized, and £12,000 extorted from them by order of the king. He
likewise laid great fines upon his judges, and other ministers, for their
corruption; the sum imposed upon eleven of them was 236,000 marks.
1289 15,000 Jews banished.
1291 Charing, Waltham, St. Albans, and Dunstable crosses erected, where the
corpse of queen Eleanor was rested on its way from Lincoln to
Westminster for interment.
1295 The Scots confederate with the French against the English.
1296 Baliol, king of Scotland, brought prisoner to London.
1298 40,000 Scots killed by the English at the battle of Falkirk. Sir William
Wallace defeated at Falkirk. Baliol released. Spectacles invented.
1301 Parliament declared Scotland subject to England.
1302 The treasury robbed of property to the amount of £100,000. Magnetic
needle first used.
1308 Crockery ware invented.
1314 The king defeated at Bannockburn, in Scotland.
1319 Dublin University founded.
1322 Knights templar order abolished. Under the accusation of heresy and other
vices, all the knights templar were seized by order of the king, in one
day. The knights templar were an order instituted by Baldwin, king of
Jerusalem, for the defence of the Holy City, and of the pilgrims that
travelled thither, and were afterwards dispersed through all the kingdoms
in Christendom. They were so enriched by the superstitious world, that
they possessed no less than 14,000 lordships, besides other valuable
lands.
1325 The queen and her adherents declared enemies to the kingdom.
1326 The nobility renounce all fealty to Edward. The king resigns his crown to his
son Edward III.
1327 The first general pardon granted at a coronation, which was afterwards
imitated by succeeding kings.
1330 Gunpowder invented. The use of guns by Berthold Swartz of Cologne in
Germany, a monk, who being addicted to the study of Chemistry, and
making up a preparation of Nitre, and other things, a spark of fire fell into
it and caused a quick and violent explosion; whereupon he made a
composition of powder, and inclosing it in an instrument of brass, found it
answer his intention, and by this accident came the invention of Guns.
1331 The art of weaving cloth brought from Flanders.
1340 Copper money first used in Scotland and Ireland. Thomas Blanket and some
other inhabitants of Bristol, set up looms for weaving those woollen
cloths that yet bear that name.
1341 Gold first coined in England.
1346 Cannon first used by the English at Cressy.
1347 So great a plague in England, that in one year there was buried in London
50,000; and there succeeded a famine and murrain. August 3rd, king
Edward took the City of Calais, which he filled with English inhabitants;
and it remained in the possession of the Crown of England 210 years
after.
1348 The Order of the Garter instituted by Edward the Black Prince, April 3. The
plague destroyed one-half of the people.
1352 The largest silver coin in England was groats.
1357 Coals first imported into London.
1362 Council obliged to plead in English.
1364 Four kings entertained at one time, by Sir Henry Picard, lord mayor of
London.
1377 The first champion at coronation. Orders to arm the clergy.
1378 The plague in the north of England. In this year Greenland was discovered.
1379 Every person in the kingdom taxed, April 25.
1381 Bills of Exchange first used. Wat Tyler’s rebellion begun May 3. 1506 rebels
hung, July 2.
1385 The French land in Scotland, in order to invade England, whereupon king
Richard went to fight them, and put Edinburgh into flames, but they
refusing to fight, he returns.
1386 Linen-weavers company first settled.
1387 The first high-admiral of England appointed. William of Wickham, bishop of
Winchester, and lord treasurer, and chancellor of England, laid the
foundation of the college in Winchester, as a nursery for his college in
Oxford.
1388 Bombs invented.
1391 A great plague and famine. Cards invented for the King of France. Charles
VI.
1392 Thirteen counties charged with treason, and obliged to purchase their
pardons. Provision seized, without payment, for the army. Duke of
Lancaster landed, and declared his pretensions to the crown, July 4.
Richard confined in the tower, August 20. Resigned his crown, September
29. In this reign piked shoes were worn tied with ribands and chains of
silver to the knees. Ladies began to ride on side saddles, before which
time they used to ride astride like men.
1399 Geoffrey Chaucer, the poet, died. A conspiracy formed to restore Richard.
1400 Richard II murdered in Pontefract Castle. Emperor of Constantinople visited
England.
1403 The battle of Shrewsbury, July 22, gained by Henry and the valour of his
sons.
1405 Great guns first used in England, at the siege of Berwick.
1407 A plague destroyed 30,000 persons in London.
1409 Wickliffe’s doctrine condemned.
1414 King Henry sends his brother, the Duke of Bedford, &c., with 200 sail of
ships, who fell upon the French fleet, sunk 500 French vessels, and took
three great Carricks of Genoa; relieved Harfleur, and so forced the French
to raise the siege. In this action many thousands of the French were
killed.
1415 The battle of Agincourt gained by Henry, with a loss of 10,000 men to the
French, killed, and 14,000 prisoners, October 25th. Henry sent David
Gam, a Welsh captain, to view the strength of the enemy, who reported,
“There were enough to be killed, enough to be taken prisoners, and
enough to run away.”
1418 Sir John Oldcastle burnt for heresy in St. Giles’s fields.
1419 Vines and sugar-cane first planted in Madeira.
1420 Henry assumes the title of King of France, on a new coin, April 18th. Kings
of France and England make a magnificent entry into Paris.
1421 The Duke of Clarence, making an inroad into Anjou, in an unhappy
engagement with the French, he and about 2,000 English were slain.
1422 The two Courts of England and France held at Paris, on Whitsunday: the
two Kings and Queens dined together in public, May 21st. In this reign it
was enacted that knights, citizens, and burgesses, should be resident in
the place for which they were chosen. The crown and jewels were
pawned to raise money for maintaining the war with France.
1422 The French King enlisted 15,000 Scots.
1424 The King of Scotland ransomed.
1430 Every person possessed of £40 per annum, obliged to be knighted.
1436 Paris taken by the English.
1437 James, King of Scotland, murdered, February 19th. So great a dearth, that
bread was made of fern roots and ivy berries.
1447 The Bodleian library at Oxford founded.
1448 Duke of York asserts his title to the crown.
1449 A rebellion in Ireland.
1450 The King and his forces defeated at Seven-oaks, by Jack Cade, in May.
Cade killed, and his followers dispersed, in June.
1453 The first Lord Mayor’s show. Richard Plantagenet, Duke of York, encounters
the Queen’s army, near Wakefield in Yorkshire, in which he was killed,
and his army routed. Edward Plantagenet, Earl of March, hearing of his
father’s death, took upon him the title of Duke of York, and in a battle, at
Mortimer’s-cross, near Ludlow, overthrew the Earls of Pembroke,
Ormond, and Wiltshire, and beheaded Owen Tudor, the King’s father-in-
law. And in another battle with the Queen, he killed the Earls of
Northumberland, and Westmoreland; the Lords Dacres, Wells, Clifford,
Beaumont, and Grey. This was the bloodiest battle that England ever
knew, for there were killed that day 36,776 men.
1454 The king defeated by the Duke of York, at Barnet.
1459 Engravings and etchings invented.
1460 The King taken prisoner at the battle of Northampton.
1461 Edward, the Duke of York, proclaimed King. Richard Plantagenet, brother to
Edward IV, created Duke of Gloucester. Henry, Margaret, their sons, and
adherents, attained by parliament, November 6th.
1463 Woollens, laces, ribands, and other English manufactures, prohibited
exportation.
1464 Henry, in disguise, taken prisoner, and conveyed to the Tower.
1469 5,000 Welsh slain at the battle of Branbury.
1470 Warwick, being offended at the marriage of Edward IV, landed September
13th, with 60,000 men from France. Edward IV flies to the Duke of
Burgundy, his brother-in-law, in Holland.
1471 King Edward, endeavouring to re-obtain the crown, encounters King Henry
in a bloody battle, upon Gladmore heath, near Barnet, and King Henry
taken prisoner a second time. On both sides were slain 10,000 men. King
Henry’s Queen, in a battle with King Edward, was taken prisoner, 3,000
on her side were slain, and her son Edward killed; and soon after, King
Henry himself was murdered by the hand of the crook-back’d Duke of
Gloucester.
1472 A plague in England destroyed more than preceding fifteen year’s war.
1475 Margaret of Anjou, ransomed for £12,500.
1481 James, King of Scotland, caused one of his brothers to be murdered.
Thomas Parr born this year, and lived 152 years. A remarkable act was
passed in this reign, which enacted what sort of dress each class of men
should wear. Another enacted that no peaked shoes should be worn.
1483 Gloucester conveyed the King to Northampton. Lords Hastings, Rivers, and
Grey beheaded. The Lord Mayor, &c., at the instigation of the Duke of
Buckingham, offered the crown to the Duke of Gloucester, who, with
affected hesitation, accepted it, June 17th. King Edward V, and his
brother, the Duke of York, murdered in the Tower. Jane Shore, concubine
to King Edward IV, and afterwards to Lord Hastings, was obliged to do
penance publicly in St. Paul’s. She was afterwards starved to death, no
person being allowed to relieve her, and died in a ditch; to which
circumstance, Shoreditch is said to owe its name. Edward V was born in
Westminster Abbey, November 4th, 1470; reigning two months and
eighteen days, was murdered in the Tower, and buried there privately. His
remains were afterwards found in 1674, and removed to Westminster.
Richard, Duke of Gloucester, (the English Nero,) proclaimed King of
England. Post-horses and stages established. Earl of Richmond landed at
Pool in Dorsetshire. Being nearly surprised by Richard, he embarked
again, and returned to Picardy.
1484 Anne, the Queen of Richard, died March 16th. Richard treats with Laudais,
the Duke of Bretagne’s prime minister, for surprising and delivering up
the Earl of Richmond. Richmond, escaping from Bretagne, went to
Angers, in Anjou.
1485 Lord Stanley raises 5000 men, and his brother 2000, with whom they joined
Richmond. The sweating sickness, raged in London.
1486 King Henry, to balance the power of the Lords, found a way to raise that of
the Commons, which ever since has carried a much greater sway than
formerly in the government.
1487 Lambert Simnel, who personated the Duke of York, was made a scullion in
the King’s kitchen. The star chamber instituted.
1488 The King of Scotland, James III, killed by his subjects. Cape of Good Hope
discovered.
1489 Maps and sea charts first brought into England by Bartholomew Columbus.
1491 The Greek language first introduced into England.
1492 3rd August, Columbus set sail from Palos, a port of Spain, and on the 12th
of October, to his unspeakable gratification, he made his first discovery in
the New World. This was one of the Bahama Islands, called by the
natives Guanahani, named by Columbus St. Salvador, and afterwards, by
some unpardonable caprice, called by the English Cat Island. He landed
the same day, took possession of it in the name of the Spanish
sovereigns, and assumed the titles of Admiral and Viceroy, which had
been awarded to him before he sailed from Europe.
1493 15th March. Columbus arrived in Spain after a stormy and dangerous
voyage, having taken not quite seven months and a-half to accomplish
this momentous enterprize.
1494 Poyning’s law, which enacted that the statutes in England, respecting the
English, should be observed in Ireland likewise, first instituted by Sir
Edward Poyning.
1495 Cicely, Duchess of York, mother to King Edward IV, died, being very old,
who had lived to see three Princes born of her body, crowned, and four
murdered.
1497 Perkin Warbeck besieged Exeter. The passage to the Indies by the way of
the Cape of Good Hope discovered. 3rd July, John Cabot discovered
Newfoundland. He sailed from the Port of Bristol, in the spring of 1497,
and, on the 3rd of July, discovered the coast of Labrador. The opposite
Island, now called Newfoundland, they called St. Johns, having landed
there on St. John’s day. To the mainland they gave the name of Terra
prima vista—or Primavista (first seen). The English navigators thus
reached the continent of North America only five years after Columbus
had discovered the West Indies, and more than a year before he had
landed on the continent or main land.
1499 Perkin Warbeck taken and hung at Tyburn, and the last Earl of the
Plantagenet line was beheaded on Tower-hill, November 28th.
1500 A plague in London, which destroyed 30,000 of its inhabitants. A marriage
was concluded between James IV, King of Scotland, and Margaret, the
daughter of King Henry VII, which afterwards united England and
Scotland under one King.
1505 Shillings first coined in England.
1513 Earl of Surrey gained the battle of Flodden-field, over the Scots, whose
King, James IV, fell in the contest. King Henry invades France in person,
takes Terwin and Tournay, at the siege of which, the Emperor Maximilian
served under the King’s pay. At which siege likewise, was fought that
battle called the battle of Spurs, because the English put some of the
French troops to flight who made great use of their spurs.
1514 Enacted that surgeons should not sit on juries, nor be employed in parish
offices.
1517 Oxford depopulated by stagnated waters. Martin Luther began the
reformation in Germany.
1521 King Henry derived the title to him and his successors of Defender of the
Faith, from writing a book against Luther. Musquets first invented. Mexico
city yielded, after a prolonged siege, to Cortez, in August.
1522 Magellan performed his voyage under the auspices of Charles V, of Spain.
He set sail from Seville, in Spain, in August, 1519. After spending several
months on the coast of South America, searching for a passage to the
Indies, he continued his voyage to the South, passed through the strait
that bears his name, and after sailing three months and twenty-one days,
through an unknown ocean, he discovered a cluster of fertile islands,
which he named the Ladrones, or the Islands of Thieves, from the
thievish disposition of the natives. The fair weather and favourable winds
which he experienced induced him to bestow on this the name of the
Pacific, which it still retains. Proceeding from the Ladrones, he discovered
the islands which were afterwards called the Philippines in honour of
Philip, King of Spain, who subjected them forty years after the voyage of
Magellan. Here, in a contest with the natives, Magellan was killed, and
the expedition was prosecuted under other commanders. After taking in a
cargo of spices at the Moluccas, the only vessel of the squadron then fit
for a long voyage, sailed for Europe by the way of the Cape of Good
Hope, and arrived in Spain in September, 1522.
1530 The palace of St. James built.
1535 Brass cannon first cast in England by John Owen. Jacques Cartier
discovered the St. Lawrence on that Saint’s day. He explored the north-
east coast carefully, and, passing through the Strait of Belleisle, traversed
the great Gulf of the St. Lawrence, and arrived in the Bay of Chaleurs in
July. He was delighted with the peaceable and friendly conduct of the
natives, “who,” says Hakluyt, “with one of their boats, came unto us, and
brought us pieces of seals ready sodden, putting them upon pieces of
wood: then, retiring themselves, they would make signs unto us, that
they did give them to us.” From this hospitable place, where the natives
seem to have displayed some of the politeness of modern society,
Jacques Cartier proceeded to Gaspé Bay, where he erected a cross thirty
feet high, with a shield bearing the three fleurs-de-lis of France, thus
taking possession in the name of Francis the First. He carried off two
natives from Gaspé, who were of great use to him on his succeeding
voyage. It appears, however, that it was with their own consent, as they
allowed themselves to be clothed in shirts, coloured coats and caps, and
to have a copper chain placed about their neck, “whereat they were
greatly contented, and gave their old clothes to their fellows that went
back again.” Cartier coasted along the northern shores of the Gulf, when,
meeting with boisterous weather, he made sail for France, and arrived at
St. Malo on the 5th of September. This celebrated navigator deserves
especial notice, inasmuch as he was the first who explored the shores of
Canada to any considerable extent, and was the very first European who
became acquainted with the existence of Hochelaga, and in 1535 pushed
his way through all obstacles till he discovered and entered the village
which occupied the very spot on which now stands the city of Montreal.
1536 376 monasteries suppressed.
1539 Leaden pipes to convey water invented.
1540 645 religious houses seized, and their property, amounting to £161,000,
given to the King. The number of monasteries suppressed in England and
Wales, were 313, Priories 290, Friaries 122, Nunneries 142, Colleges 152,
and Hospitals 129; in all 1148.
1541 1st voyage to India by an English ship.
1543 Mortars and cannon first cast in iron.
1544 Pistols first used.
1545 William Foxley slept fourteen days, and lived forty-one days after.
1547 The vows of celibacy before taken by priests, annulled, and the communion
ordered to be administered in both kinds. Evening prayers began to be
read in English in the King’s chapel, April 16th. The Scots refusing to
marry their young Queen to King Edward (according to their promise in
his father’s life-time), the protector enters Scotland with an army of
12,000 foot, and 600 horse, and fights them in Pinkey-field, near
Musselburgh, and kills 14,000 Scots, and takes 1500 prisoners, having
lost but sixty of his own men.
1548 Some ceremonies were now abrogated, and an order of council against the
carrying of candles, on Candlemas-day, ashes on Ash-Wednesday, and
palms on Palm-Sunday.
1549 Telescopes invented.
1551 The sweating-sickness broke out this year In England with such contagion,
that 800 died in one week of it in London. Those that were taken with it
were inclined much to sleep, and all that slept died; but if they were kept
awake a day, they got well. A college founded in Galway in Ireland.
Common-prayer books established by act of parliament. Monks and nuns
allowed inheritances. Sternhold and Hopkins translated and put the
Psalms into verse.
1553 There was so great a plenty of malt and wheat, that a barrel of beer with
the cock sold for six-pence, and four great loaves for one penny. The King
founded St. Bartholomew’s Hospital, Bridewell, improved the Hospital of
Christchurch and St. Thomas’ Hospital, Southwark. Judge Hales, in his
circuit into Kent, required the justices to see to the execution of King
Edward’s laws: for which he was committed, and removed from prison to
prison, and threatened so, that he attempted to cut his own throat, and
at last drowned himself.
1553 Spitzbergen, the White Sea, and Nova Zembla, discovered by the English.
1554 The laws against Lollards and Heretics were revived, and the statutes of
Mortmain repealed. There was at this time a discovery in London of the
imposter of the Spirit of the Wall, who, by the help of a whistle, uttered
several things relating to religion, and the state, through a hole in a wall.
It was found to be Elizabeth Croses, and one Drake, her accomplice, who
were both made to do penance for it publicly at St. Paul’s. Scory, bishop
of Chichester, renounced his wife, and did penance for his marriage. It is
supposed there were 12,000 of the clergy deprived for being married,
and most of them were judged upon common fame, without any process,
but a citation.
1555 The church lands, in the Queen’s possession, restored. Coaches first used in
England.
1556 300 Protestants burnt for heresy.
1557 This year began with a visitation of the Universities. Commissioners were
sent to Oxford, where they burnt all the English Bibles and heretical
books they could find; and took up the body of Peter Martyr’s wife, who
they said was a heretic, and buried it in a dunghill. And at Cambridge,
they dug up the bodies of Bucer and Fagius, two heretics, and tied their
coffins to stakes, and burnt them and their heretical books together.
Cardinal Pole died November 15th.
1576–77–78 Three voyages by Frobisher in search of a North-west passage.
Greenland explored.
1580 Drake, the first English circumnavigator.
1584 Virginia discovered by Sir Walter Raleigh.
1587 Davies’ Straits discovered by Davies, an English navigator. February 9th.
Execution of Mary, Queen of Scots, at Fotheringay Castle.
1588 Destruction of the Spanish Armada.
1595 Falkland Islands, discovered by Hawkins.
1596 The first trading expedition to the East Indies.
1599 East India Company. Chauvin made two voyages to Tadousac.
1603 Death of Queen Elizabeth on 24th March, and accession of James VI.
1604 The present translation of the Bible made.
1605 The gun-powder plot discovered. The channel for the New River allowed to
be cut. 97,304 person died in London, this year, whereof 68,596 died of
the plague.
1608 Virginia planted by the English. Champlain returned to Canada, and Quebec
founded 3rd July.
1609 East India company’s patent removed. Chelsea college founded. Alum
brought to perfection by Sir J. Bouchier. Silk-worms first brought into
England.
1610 Thermometers invented. King Henry IV of France murdered at Paris, by
Ravillac, a Romish priest.
1611 Bartholomew Legat was condemned by the convocation for an Arian
heretic. Legat was burnt at Smithfield for an Arian.
1612 Edward Wightman of Burton, burnt at Lichfield for a heretic.
1614 Sir Thomas Overbury poisoned in the Tower. The New River brought to
London. Champlain returned to France. An inundation of the sea
overflowed an extent of twelve miles in Norfolk and Lincolnshire.
1618 Sir Walter Raleigh is executed for high treason, at the instigation of the
Spanish ambassador. The poet Shakspeare flourished during the
beginning of this and the latter part of the preceding reign. Synod of Dort
began: who generally agreed to condemn the doctrines of Arminius,
concerning election, reprobation, and the universality of Christ’s death,
and man’s redemption by it.
1623 The fatal Vespers at Black-Friars.
1625 A plague in London destroyed 35,417 of its people.
1626 The king raised money by sale of the crown lands, loans, and ship-money.
1628 Dr. Lamb murdered in the streets of London. The city fined for Dr. Lamb’s
death, £6,000.
1629 Quebec surrendered to Sir David Kirkt.
1635 Thomas Parr, reported to be aged 152 years, died November 15.
1640 The fatal Long Parliament, began November 3. An act to abolish the Star-
chamber.
1641 The princess Mary married to William of Nassau, prince of Orange, at
Whitehall. The earl of Strafford attained, May 8: executed May 12. A bill
passed for pressing soldiers.
1642 Edge-Hill fight: the number of the slain amounted to above 5,000, whereof
two-thirds were conceived to be of those of the parliament party, and a
third part of the king’s. June 17th, Montreal founded by Champlain. In
the year 1640 the King ceded the whole Island of Montreal to the St.
Sulpicians and in the following year M. de Maisonneuve brought out
several families from France, and was appointed governor of the island.
On the 17th of June, 1642, the spot destined for the city was consecrated
by the Superior of the Jesuits, the “Queen of Angels” was supplicated to
take it under her protection, and it was named after her “la Ville Marie.”
On the evening of this memorable day, Maisonneuve visited the
mountain. Two old Indians who accompanied him, having conducted him
to the summit, told him that they belonged to the nation which had
formerly occupied the whole of the country he beheld, but that they had
been driven away, and obliged to take refuge amongst the other tribes,
except a few who, with themselves, remained under their conquerors.
The governor kindly urged the old men to invite their brethren to return
to their hunting-grounds, assuring them they should want for nothing.
They promised to do so, but it does not appear that they were successful.
In the year 1644, the whole of this beautiful domain became the property
of the St. Sulpicians of Paris, and was by them afterwards conveyed to
the Seminary of the same order at Montreal, in whose possession it still
remains.
1644 York relieved by Prince Rupert, after which happened the fight on Marston-
Moor, in which action about 7000 were slain, and 3000 of the King’s party
taken prisoners, with all their baggage.
1645 The fatal battle of Naseby, in which 600 private soldiers were killed on the
King’s side, and 4500 were taken prisoners; 3000 horse, &c. Montrose
defeated the Scotch army at Ketsith, near Glasgow, in Scotland. Cromwell
made lieutenant-general.
1646 The whole order of archbishops and bishops abolished, October 9th.
1646–7 Charles delivered up by the Scotch to the English for the consideration of
£400,000, January 30th.
1648–9 The King sentenced to be beheaded as a tyrant, traitor, murderer, and
public enemy.
1649 Oliver Cromwell made Lord Lieutenant of Ireland, August 13th.
1650 The Marquis of Montrose defeated in Scotland, taken prisoner, sentenced,
and barbarously murdered.
1651 Oliver Cromwell invaded Scotland, July 22nd. Charles II defeated at
Worcester by Oliver, September 3rd.
1653 Oliver chosen protector of England, December 16th. The Rump parliament
turned out by the army, which had sat twelve years six months and
thirteen days. Scotland and Ireland united in one commonwealth with
England, April 12th. Jamaica taken by the English.
1655 Cromwell dissolved the parliament.
1656 Oliver would not suffer the French King to call himself the King of France.
1656–7 A plot to destroy Oliver discovered.
1657 Doctor William Harvey, the first discoverer of the circulation of the blood,
died January 5th.
1659 The House of Commons shut up, and entrance denied its members. The
Rump sat again, May 7th. The Rump parliament turned out again by
Lambert, October 18th. The Rump parliament re-admitted, December
26th.
1660 Oliver Cromwell’s corpse hung at Tyburn, December 2nd. The Long
parliament dissolved, and another called, to be holden at Westminster,
April 25th.
1661 The body of the noble Marquis of Montrose taken up, and interred in great
state.
1662 152 slaves redeemed from Algiers.
1663 Laird Warreston executed at Edinburgh, according to a sentence in
parliament, on a gibbet twenty-two feet high.
1665 90,000 people destroyed by the plague in London.
1666 Great fire in London, September 2nd, when 13,200 dwelling-houses were
destroyed. The Dutch and English fleets fight for four days, neither party
having the advantage. They engage again, and the English obtain the
victory.
1669 Death of the poet Sir John Denham.
1670 The church of Quebec constituted a bishopric.
1671 The exchequer shut for want of money. Blood attempted to steal the crown
from the Tower.
1674 King Charles received from France a pension of £100,000 per annum.
Milton, the poet, and the Earl of Clarendon died.
1676 Carolina planted by English merchants.
1678 Statue at Charing-Cross erected.
1679 The meal-tub plot.
1683 The charter of London taken away by Charles. The Rye-house plot. Lord
Russel beheaded on a charge of high treason. Algernon Sidney
beheaded, for writing a libel never published, November 21st.
1684 The Buccaneers of America, about 100 in number, with the assistance of
some Indians, went into the South seas, and made a bold attack on the
Spaniards. Bombay, in the East-Indies, was surrendered to Sir Thomas
Grantham, for the use of the East-India company.
1685 Duke of Monmouth proclaimed King at Taunton Dean, defeated at
Sedgemore, taken and beheaded.
1685 Justice Jeffries and General Kirk exercise great cruelties on the adherents of
Monmouth.
1686 The Newtonian philosophy published. Kirk, at Taunton, while at dinner with
his officers, ordered 30 condemned persons to be hanged, namely, 10 in
a health to the King, 10 to the Queen, and 10 to Jeffries; but one action
the most cruel, was, a young girl throwing herself at his feet to beg her
father’s life, he made her prostitute herself to him, with a promise of
granting her request; but having satisfied his lustful desire, was so
inhuman as out of the window to show the poor unfortunate girl her
father hanging on a sign-post: the spectacle so affected her, that she
went distracted. The King encamped 15,000 men on Hounslow heath.
1688 Seven bishops committed to the Tower for not countenancing popery. The
city of London lent the Prince of Orange £20,000, January 10. The
parliament declared James’s abdication. James escorted to Rochester by
a Dutch guard, and sailed to France. James landed in Ireland with an
army, and assembled a parliament. Brass money coined by James in
Ireland. Bill of rights passed. Every hearth or chimney paid two shillings
per annum. King William and Queen Mary crowned at Westminster, April
11. The Hanover succession first proposed, May 31.
1690 The battle of the Boyne in Ireland, where James was finally defeated by
William, and obliged to embark for France, July 1.
1691 William III took his seat as Stadtholder in Holland. The Queen issues out
her royal proclamation for the more reverend observing the Sabbath day,
and against profane cursing and swearing. A terrible battle between the
Imperialists and Turks, near Salenkemen, in the principality of Sclavonia:
in which the Imperialists had about 7,000 killed and wounded, and a
great many good officers; but the Turks lost 18,000 men, and almost all
their officers killed, wounded, or taken prisoners. Five captains of Admiral
Benbow’s squadron in the West-Indies, were tried on board the Breda, at
Port-Royal, in Jamaica, for cowardice and breach of orders, in an
engagement with Ducasse. The Irish defeated at the battle of Aughrim, in
Ireland.
1692 The French fleet destroyed at La Hogue and other places by Admiral
Russell. A terrible earthquake in the island of Jamaica in the West-Indies,
which almost entirely ruined the town of Port-Royal, the best of all the
English plantations.
1692 37 cities, towns, and large villages, and about 130,000 people destroyed in
the kingdom of Naples, by an earthquake, February 11. The massacre of
Glencoe, in Scotland.
1692 James’s descent on England frustrated; the destruction of the French fleet,
May 19.
1693 The English fleet defeated by Tourville.
1694 Queen Mary died of the small-pox. The bank of England incorporated.
1694–5 Discipline of the Church restored. Commissioners appointed to direct the
building and endowment of Greenwich hospital.
1695 Duties imposed on births, marriages, burials, bachelors, and widowers.
1695–6 Guineas went at the rate of thirty shillings. Six-pence per month
deducted out of every seaman’s wages, for the support of Greenwich
hospital.
1696 Czar of Muscovy, Peter the Great, came into England, and remained
incognito. The window tax first levied.
1700 The New-Style introduced by the Dutch and Protestants in Germany.
1700–1 Earl John, of Marlborough, appointed General of the foot, June 1, and
Commander-in-Chief of His Majesty’s forces in Holland. King James II
died of a lethargy at St. Germain’s in France, in the sixty-eighth year of
his age, September 6.
1702 King William died at Kensington in the fifty-second year of his age, and the
fourteenth of his reign, March 8.
1702 Captain Kirby and Captain Wade were condemned to die, and being sent to
England, were shot on board a ship at Plymouth, not being suffered to go
on shore. Admiral Benbow, who had his leg shattered with a great shot in
the engagement with Ducasse, died of his wounds soon after he had the
Captains condemned.
1703 The Earl of Marlborough chosen Captain General of Queen Anne’s army. A
dreadful tempest in England. The old and new East-India companies
united.
1704 Gibraltar taken in three days, by Admiral Rook. The battle of Blenheim
gained by the Duke of Marlborough and Prince Eugene. The French fleet
defeated at Malaga, by the English.
1705 The colours and standards taken at Blenheim, hung in Westminster Hall.
The English take Barcelona from the Spanish.
1706 The battle of Ramillies gained by Marlborough. The colours and standards
hung at Guildhall.
1707 England and Scotland united. An interview between the Duke of
Marlborough and Charles XII. Sir Cloudesly Shovel shipwrecked on the
rocks of Sicily.
1708 The battle of Malplaquet gained by the Duke of Marlborough and Prince
Eugene. The French defeated at Oudenarde by Marlborough and Prince
Eugene. The first parliament of Great Britain met April 24. Dr. Sacheverel
impeached by the Commons for high crimes and misdemeanors.
1709 Charles XII defeated by the Russians at Pultowa.
1712 Robert Walpole committed to the Tower for bribery. Richard Cromwell, son
of Oliver Cromwell, died, aged ninety.
1714 Mr. Steele expelled the House of Commons for writing the Englishman and
the Critic. £5,000 offered to apprehend the Pretender.
1714 George I arrived at Greenwich from Hanover.
1715 The Pretender proclaimed as James VIII in Scotland, by the Earl of Mar,
who assembles forces.
1716 The tide forced back by a strong westerly wind for one day and night, and
the Thames lay perfectly dry both above and below the bridge. A dreadful
fire happened in Thames street, near Bear-key, by the imprudence of a
boy who was making squibs and rockets, which consumed upwards of
120 houses.
1717 The Prince of Wales banished the court.
1718 James Shepherd, a lad of eighteen, executed for conspiring the King’s
death. Charles XII of Sweden killed at the siege of Frederickshall.
1719 The Pretender received at Madrid as King of Great Britain. The Mississippi
scheme at its height in France. The English and French invaded Spain by
land, and took the towns of Fontarabia, St. Sebastian, and St. Antonio,
and reduced the province of Gui Puocoa.
1720 South-sea stock rose 400 per cent, and continued to rise until July, when it
rose to 1,000 per cent.
1721 Several persons ruined by the South-sea stock falling to 150 per cent.
Several members of parliament expelled for being concerned in the
South-sea bubble, and their estates confiscated for the use of the
sufferers.
1725 The Lord Chancellor (Earl of Macclesfield) displaced, impeached, and fined
£30,000 for corruption. Jonathan Wild, a notorious thief-taker, executed.
1727 The Spaniards besiege Gibraltar. Sir Isaac Newton died, aged 85.
1729 Deaths of Dr. S. Clarke, Sir Richard Steele, Congreve the poet, and the
noted John Law.
1731 Deaths of Dr. Atterbury, and Defoe.
1732 Death of Gay, the poet and fabulist.
1737 A comet appeared. Death of Howe.
1739 Admiral Vernon takes Porto Bello.
1742 Sir Robert Walpole resigned, after holding his places twenty-one years.
1743 King George defeated the French at Dettingen.
1744 Admiral Anson returned with £1,500,000 which he had taken in the
Acapulca ship. Deaths of Pope the poet, and Roger Gale. Prague taken by
the King of Prussia.
1745 The Duke of Cumberland defeated at Fontenoy. Battle of Preston-Pans.
Death of Dean Swift.
1746 The rebels defeat the royal army at Falkirk. The Pretender totally defeated
by the Duke of Cumberland at Culloden. Several Lords and others
executed for rebellion.
1747 The French fleet defeated by Admiral Hawke.
1748 Death of Thompson, the poet.
1752 The style altered.
1755 General Braddock defeated.
1757 Admiral Byng shot for cowardice.
1758 100 French ships destroyed at St. Maloes, by the Duke of Marlborough,
called by his soldiers, Corporal John.
1759 The French defeated at Minden. Quebec taken by General Wolfe, and death
of Wolfe on the Heights of Abraham. Boscawen defeats the French off
Gibraltar, (Gabel-el-Tarifa) hence Gibraltar, which is also called the Babel
of Nations, and the Key of the Mediterranean. Guadaloupe surrendered to
the English.
1760 General Lally defeated in the East Indies. Canada surrendered to the
English.—Capitulation signed 8th September.
1762 War declared against Spain. The Hermione, a Spanish ship taken, valued at
near £1,200,000. Manilla taken from the Spaniards. Havana taken from
the Spaniards. Preliminaries of peace between England and France signed
at Fontainbleau, November 3. Martinico and Guadaloupe taken by the
French.
1763 Peace proclaimed between England, France, and Spain.
1764 The longitude found at sea by means of Harrison’s time-piece. The
massacre of Patna in the East Indies, where 4,000 of the garrison and
inhabitants were put to the sword.
1765 Otaheite discovered by Captain Willis.
1766 The American Stamp Act repealed. Gibraltar nearly destroyed by a storm.
1769 New Zealand explored by Captain Cook. Electricity of the Aurora Borealis
discovered. Stratford Jubilee held in honour of Shakspeare.
1771 Falkland islands seized by the Spaniards.
1772 Negroes adjudged free, in England. Solway moss began to flow.
1773 A large quantity of tea belonging to the East India Company, destroyed at
Boston by the citizens.
1774 The port of Boston shut up by an act of parliament. Civil war commences in
America. A violent storm, by which 40 ships were lost near Yarmouth.
Humane Society for the recovery of drowned persons instituted.
1775 Trade with America prohibited. The battles of Lexington and Bunker’s hill.
The Americans invade Canada and besiege Quebec.
1776 America declared itself independent.
1777 General Burgoyne and his army surrender to the Americans at Saratoga.
1778 War declared against France. Pondicherry taken from the French. Admiral
Keppel fights the French fleet off Ushant. The Earl of Chatham died, and
interred in Westminster Abbey.
1779 Ireland admitted to a free trade. The French make a fruitless attempt on
the island of Jersey. Their shipping destroyed in Concale Bay. An
American fleet totally destroyed off Penobscot. Pitch and tar made from
pit-coal at Bristol.
1780 Admiral Rodney defeats the Spanish fleet near Cape St. Vincent, and takes
their Admiral Laugara prisoner. Dreadful riots in London. War with Spain
and Holland. Torture abolished in France. His Majesty’s ships Andromeda,
Laurel, Deal-Castle, Thunderer, Stirling-Castle, Cameleon, and many
others, lost in a dreadful hurricane in the West Indies.
1781 Lord Cornwallis and his army surrender to the Americans and French at
York-Town. Sir Eyre Coote defeats Hyder Ally. Ceylon taken from the
Dutch. Florida conquered by the Spaniards. Engagement between
Admiral Parker and the Dutch fleet off Dogger Bank. St. Eustatius, St.
Martin, and other Dutch settlements, captured.
1782 Batavia taken by the English. The memorable attack of Gibraltar by the
French and Spaniards;—their gun-boats totally destroyed, and the
garrison relieved by a squadron of 33 ships of the line, under Lord Howe,
in the face of the combined fleets of France and Spain, consisting of 47.
Admiral Rodney defeats the French fleet in the West Indies; takes Admiral
Count de Grasse and five ships of the line. The Ville de Paris and other
French prizes lost at sea.
1783 Great Britain declares the United States of America independent. A new
planet discovered by Mr. Herschell, and called the Georgium Sidus. A new
island rose out of the ocean near Iceland.
1784 The great seal stolen. Mail coaches first established, by Mr. Raikes, of
Gloucester. Slave trade abolished in Pennsylvania, and in New England.
1785 Blanchard and Dr. Jefferies cross the English Channel, in a balloon, from
Dover, and land near Calais. M. Pilatre de Rosiere, and M. Romain, ascend
in a balloon, which takes fire and they are dashed to pieces.
1786 Margaret Nicholson attempts to assassinate the King. Frederick the Great,
King of Prussia, died. Convicts first sent to Botany Bay, and Sierra Leone.
The young Lord Gormadston clandestinely carried abroad, in order to
force him to embrace the Romish persuasion.
1787 Three American priests ordained bishops by the Archbishop of Canterbury,
The house of Peers commenced the trial of Warren Hastings, Esq., on a
charge of high crimes, &c., committed by him in the East Indies, of which
he was impeached.
1789 The abolition of the Slave trade proposed in Parliament. Beginning of the
French Revolution.
1790 War commenced in India with Tippoo Sultan.
1791 Riots at Birmingham.
1793 The Alien-bill passed in the British House of Commons. The English
evacuate Toulon.
1794 The Habeas Corpus Act suspended. Lord Howe defeats the French fleet off
Ushant.
1795 Mr. Hastings’ trial ended by his acquittal. The Cape of Good Hope taken by
the British forces. Ceylon taken by the British.
1796 The East India Company votes an indemnification and recompense to Mr.
Hastings.
1797 A mutiny of the British fleet at Portsmouth and the Nore suppressed. The
Dutch fleet beaten and captured by Lord Duncan.
1798 Ireland in open rebellion. Lord Nelson totally defeated the French fleet in
the battle of the Nile. The French fleet defeated by Sir J. B. Warren.
1799 Seringapatam taken by General Harris and Sir David Baird, and Tippoo
Sultan killed. The French under Bonaparte defeated by Sir Sidney Smith
at Acre. The expedition of the British against Holland. The British troops
evacuate Holland.
1800 Vote of the Irish House of Commons agreeing to the Union of Great Britain
and Ireland.—Similar vote of the House of Lords. Malta taken by the
British forces.
1801 Mr. Pitt resigns, after being minister 18 years. Battle of Alexandria,—the
French defeated and Sir Ralph Abercrombie killed. Battle of Copenhagen,
the Danish fleet taken and destroyed by Lord Nelson. Taking of Cairo and
Alexandria, by the British troops.
1802 Definitive treaty with France signed at Amiens.
1803 Execution of Col. Despard for high treason. Dissolution of the peace with
France, May. Insurrection in Dublin; Habeas Corpus suspended, and
Martial Law proclaimed. Defeat of Row Scinda and Berar Rajar at Ajunty,
by General Arthur Wellesley. The British troops enter Delhi and the Great
Mogul puts himself under their protection.
1804 Mr. Pitt resumes his situation as Prime Minister.
1806 The Spaniards declare war against Great Britain. Lord Nelson defeats the
combined fleets of France and Spain at Trafalgar; takes twenty sail of the
line, and is killed in the engagement. Sir R. Strachan takes four French
ships of the line, off Cape Ortegal.
1806 Death of William Pitt; his debts discharged at the public expense, and a
statue decreed to his memory. Admiral Duckworth captures and destroys
five French ships of the line. Sir John Stuart defeats the French under
Regnier at Maida in Calabria. Surrender of Buenos Ayres to General
Beresford and Sir Home Popham. French squadron of five frigates
captured by Sir Samuel Hood. Death of Charles James Fox. Rupture of a
negotiation for peace with France, and return of Earl Lauderdale.
Recapture of Buenos Ayres by the Spaniards. The slave trade abolished
by act of Parliament.
1807 Copenhagen bombarded, and the Danish fleet surrendered to the British,
under Lord Cathcart and Admiral Gambier. South America evacuated by
the British. The British troops evacuate Egypt. The island of Madeira
surrendered to Great Britain in trust for Portugal.
1808 The French prohibit all commerce with Great Britain. Battle of Vimiera in
Portugal; the French under Junot defeated by Sir Arthur Wellesley.
1809 The French defeated at the battle of Corunna; Sir John Moore killed. The
French fleet in Basque roads destroyed by Lord Cochrane. Senegal
surrendered to the British. The battle of Talavera; the French defeated by
Sir Arthur Wellesley. The 50th anniversary of the King’s reign celebrated
as a jubilee. The French fleet in the Mediterranean defeated by Lord
Collingwood.
1810 An attempt made to assassinate the Duke of Cumberland; Sellis, the Duke’s
valet, found with his throat cut. Murat’s army in Sicily defeated by
General J. Campbell. Battle of Busaco; the French defeated by Lord
Wellington. Capture of the Isle of France by the British. This island has
ever since remained in the hands of the British. Its other name is
Mauritius, famous for Peter Botte Mountain and its fine sugar.
1811 The Prince of Wales appointed Regent. Battles of Barossa, Albuera, &c. in
which the French were beaten with great loss. Isle of Java capitulated to
the British arms.
1812 Ciudad Rodrigo taken by storm, by Lord Wellington. Right Honorable
Spencer Percival, prime minister of Great Britain, assassinated by John
Bellingham. Battle of Salamanca, and defeat of the French.
1813 Great battle of Vittoria in Spain, in which Lord Wellington totally defeats the
French under Joseph Bonaparte and Marshal Jourdan. Defeat of Marshal
Soult, in Spain, with the loss of 15,000 men, by Lord Wellington.
1814 A fair on the Thames, it being frozen over above the London bridges, Feb.
2. Bourdeaux surrenders to Lord Wellington. Peace between England and
France. The allied Sovereigns visit London. City of Washington taken by
the British army under General Ross. Treaty of peace between England
and America, Dec. 24. Joanna Southcott an impostor, died; and, with her,
the hopes of the promised Shiloh, and all her other prophecies.
1815 Bonaparte sailed from Elba, and landed with 1,000 men at Cannes, in
France. Bonaparte enters Paris, March 21. An attempt made by Margaret
Moore to steal the Crown from the Tower. Memorable battle of Waterloo,
June 17, 18; Bonaparte fled; the Duke of Wellington’s horse killed under
him. Bonaparte sailed for St. Helena, August 7. Submission of the island
of Ceylon to Britain. Bonaparte landed at St. Helena, October 16. The
English repulsed at New Orleans, with the loss of several thousand in
killed and wounded, including several generals. General Jackson
commanded the Americans. General Packenham was killed. A column of
light appeared in the north-east, so vivid as to alarm many persons. By
the explosion of a coal-pit near Newbattle, in the county of Durham, 70
persons perished. Bonaparte resigns the government to a provisional
council. In the colliery above-mentioned at Newbattle, a steam engine
burst, and 57 persons were killed or wounded.
1816 Princess Charlotte of Wales married, to Prince Leopold of Saxe Coburg, May
2. Sir Humphrey Davy invented a Safety Lamp to prevent the accidents
which happen in coal-mines from fire damp.
1817 The Princess Charlotte died in child-birth, having been delivered of a still-
born child. Steamboats generally adopted for river navigation in America
and Europe. The magnetic needle, which had for many years taken a
western declination from the meridian, returned towards the north.
1818 The Queen of Great Britain, Charlotte of Mecklenburg-Strelitz, died Nov. 21.
Two expeditions to penetrate the North-pole sailed, one to the north-
east, and the other to the north-west, but neither succeeded. The
kaleidoscope, a new optical instrument, invented by Dr. Brewster of
Edinburgh. Three systems of education in this year claimed public
attention: that of mutual instruction propagated by Dr. Bell and Mr.
Lancaster; the interrogative or intellectual system of questions without
answers; and that of Mr. Pestalozzi by oral questions. Belzoni transported
from Egypt to England the statue of Memnon. The Duke of Clarence
married to the Princess of Saxe Meiningen; and the Duke of Kent to a
Princess of Saxe Coburg. For two or three days the metropolis, as well as
the country round, were enveloped in a thick impenetrable fog, which
obstructed all travelling, and caused a number of fatal accidents. The
Duke of Richmond died in Canada, from the bite of a rabid fox.
1819 Messrs. Perkins and Co., of Philadelphia, introduced into London a mode of
engraving on soft steel, which, when hardened, will multiply fine
impressions indefinitely. Many distressed persons embarked, under the
sanction of government, to establish a new colony at the Cape of Good
Hope. Southwark bridge opened, making the sixth metropolitan bridge
over the Thames. Forty persons killed by the explosion of a mine near
Newcastle. A shoal of young whales appeared in Dungannan Bay, forty
taken by the fishermen. A whirlwind at Aldborough, Suffolk, carried up a
quantity of barley from a field to a great height. Another expedition was
fitted out to try a north-west passage to the Pacific Ocean. Field Marshal
Prince Blucher died.
1820 Lieutenant Parry returned from his voyage to attempt the discovery of a
north-west passage: he reached the 10th degree of west longitude,
where he passed one winter in latitude 74, and returned for further
supplies. Lamented death of H.R.H. the Duke of Kent. Death, in Windsor-
castle, of George III, in the 82d year of his age, and 60th of his reign.
George IV held his first court in Carlton-house. Takes oath to maintain
the Church of England. Oaths of allegiance administered. Cato-street
conspirators arrested. Thistlewood and his associates executed before
Newgate. Regent’s canal from Paddington to Limehouse opened.
Extraordinary solar-eclipse; central and annular in the interior of Europe.
An Estadfod, or assembly of Welch bards, in Wrexham, North Wales.
Lieutenant Parry returns from his voyage of discovery in the seas on the
north of North America.
1821 A Pedo-motive machine invented by Dr. Cartwright for travelling the public
roads without the aid of horses. A mammoth’s bones found by Captain
Vetch, on the west bank of the Medway, near Rochester. Mr. Kent of
Glasgow, invented a machine for walking on the surface of the water, at
the rate of three miles an hour. A penknife, containing 2,016 blades, was
presented to the Queen, by a Sheffield manufacturer; another was
afterwards made containing 1,821 blades. Duel between Mr. Scott, of the
London Magazine, and Mr. Christie, of an Edinburgh Magazine, in which
the former was mortally wounded. News received of a dreadful massacre
in Manilla, arising from religious fanaticism. A gambling-house, in London,
entered by the police, and about 70 individuals held to bail. The
Discovery-ships sailed from Deptford, for the American Arctic Seas. Sale
of a collection of Pictures, by Sir Joshua Reynolds, which produced
£15,000. A bog burst forth from Kilmalady, in Ireland, and in an hour
covered 100 acres from 20 to 60 feet deep; it proceeded to a great
extent, 200 yards wide, and 80 feet deep, at the rate of two yards per
hour. Roads and bridges were covered, communications cut off, and great
damage done. Queen Caroline died at Hammersmith, after an illness of
eight days. Loss of the Juliana, East-Indiaman, in the Margate-roads, in
which 38, out of the 40 individuals on board, perished.
1822 The King surrendered £30,000 per annum of the civil list. A coroner’s jury
decided that publicans are legally bound to receive into their houses all
persons in extremity. Fifteen thousand Greeks massacred in the island of
Scio, by the Turks. A south-west gale so retarded the flow of the tide in
the Thames, that it was fordable at London bridge. Subscriptions opened
for the starving Irish peasantry, which amounted to £300,000. Dreadful
cases of misery and oppression published. Upwards of 800 Greek virgins
exposed in the slave markets, and 20,000 Christians slaughtered in
various villages. The Marquis of Londonderry, cut his throat at his house,
North Cray. Mr. Canning appointed Secretary of State, in lieu of the
Marquis of Londonderry. Grand eruption of Mount Vesuvius, the most
tremendous since 1794. Fonthill abbey purchased by Mr. Farquhar, for
£330,000. Sir William Herschell, the celebrated Astronomer, died. Canova,
the celebrated Sculptor, died. Madame Lætitia Bonaparte, mother of the
late Emperor of France, died.
1823 George IV presented to the nation the library of his late father, at
Buckingham House, consisting of 120,000 vols. An insurrection of the
Negroes at Martinique detected: several planters had died by poison. Two
hundred Negroes ordered for execution. Captain Parry arrived from his
exploratory voyage to the Polar regions; he had failed in the chief object
of the expedition. Three grand Musical Festivals held within a month, at
York, Birmingham, and Gloucester, produced the enormous sum of
£30,500. By the melancholy accident from fire damp, at the William Pitt
colliery near Whitehaven, 14 men, 16 boys, and two girls, lost their lives;
17 horses were also killed. Dr. Jenner, discoverer of Vaccination, died.
Mrs. Radcliffe, authoress of the Mysteries of Udolpho, &c., died. At
Rochetts, Earl St. Vincent died. At Kincardine, Admiral Lord Keith, died. At
Rome, Pope Pius the Seventh, died.
1824 A subterraneous forest of oak was discovered, on the shores of the Solway
Frith, beyond Brough, imbedded in a stiff blue clay; the trees were of
large dimensions, and the wood so perfect as to be scarce perceptible
from new timber, although it must have lain there many thousands of
years. Mr. Mantell discovered, in the iron sand-stone of Sussex, the teeth
of a herbivorous reptile of gigantic magnitude, being of the lizard tribe;
from a thigh bone found, it must have equalled the elephant in height,
and been more than 60 feet long. The pictures of J. J. Angerstein, 38 in
number, purchased by Government for £57,000 to begin a national
gallery; Sir G. Beaumont liberally presented his collection to the public for
that purpose. The Hecla, discovery ship, with Captain Parry left her
moorings on a voyage of discovery to the Arctic region. Mr. Harris,
accompanied by Miss Stocks, ascended in a balloon, when the former
was killed by being thrown from the car. The remains of Lord Byron were
conveyed from London, amidst a concourse of people, for Newstead
Abbey. A copy of Columbus’ letter to the King of Spain, on the discovery
of America, sold for 34 guineas. Particulars were received respecting the
death of the celebrated traveller Belzoni, at Gato on his journey to
Timbuctoo. Mr. Sadler, jun., the aëronaut, was killed on descending in his
balloon, near Blackburn in Lancashire. The enormous timber ship, called
the Columbus, arrived at Blackwall, from the river St. Lawrence, being
300 feet long, 50 broad, and 30 deep. Patrick Grant died, aged 111; to
this venerable Highlander, His Majesty had granted a pension of a guinea
a week.
1825 In January, wool was exported from England to the United States of
America, being the first instance for two centuries. Organic remains of
antediluvian animals found in a cave near Chudleigh. Steam engines in
England, representing the power of 320,000 horses, equal to 1,920,000
men, managed by 36,000 only, now add to the power of our population
1,884,000 men! A phenomenon observed on the coast of Kent, being a
cloud, resting part on the sea, extending as far as the eye could reach,
reflecting two distinct images of every vessel passing, one inverted, the
other in its proper position, apparently sailing in the air. An earthquake
happened in Algiers, when the town of Blida, was totally destroyed, and,
of a population of 15,000 persons, scarcely 300 were left alive. £2,000
granted to Mr. M‘Adam for improvement of the roads. The Tower of
Fonthill-Abbey fell, and destroyed great part of that elegant building.
1826 London was visited by such a dense fog, in the forenoon, that candles were
burned in all the shops. The abduction of Miss Turner by E. G. Wakefield.
The death of the celebrated composer, Baron Von Weber, occurred, being
in his 40th year. Mr. Canning dined with the King of France, and Sir
Walter Scott with the King of England.
1827 Canal Excavation by the plough in lieu of manual labour. It is remarkable,
that England, which usually sets the example to all Europe in the
application of machinery as a substitute for manual labour, should have
been anticipated by the small state of Wurtemberg; an extensive line of
canal having been projected, and sanctioned by the Government, an
eminent engineer constructed a set of ploughs of various forms to suit
the nature of the soil to be intersected, which, by the aid of from eight to
twelve horses, excavated the line of canal, at less than a fourth of the
price which would have been expended in manual labour. His Royal
Highness the Duke of York expired. Will of Mr. Rundel, the silversmith,
proved, whose personal property amounted to £1,200,000. The steam
vessel George the Fourth left Portsmouth for Africa. Mr. Canning
appointed chancellor of the Exchequer, April 24. Mr. Canning expired,
Aug. 8. Lord Goderich appointed Premier. Death of Dr. Good, F.R.S.,
author of various works on Science, &c. Death of Rebecca Fury, of
Falmouth, Jamaica, aged 140. Clapperton’s second voyage to Africa.
Parry’s attempt to reach the North Pole over the ice without success. Lord
Liverpool died, George Canning succeeded. Intervention of England,
France, and Russia in the affairs of Greece: battle of Navarino.
Premiership and death of Canning.
1828 Duke of Wellington premier. Russian invasion of Turkey. Capo d’Istria
President of Greece: a French army in the Morea. Don Miguel usurps the
throne of Portugal.
1829 The Russian Field-Marshal Diebitsch crosses the Balkan. Treaty of
Adrianople. Independence of Greece recognized by Turkey. Catholic
emancipation in England.
1830 Accession of William IV. Algiers taken by the French. July 25th, revolution at
Paris: abdication of Charles X: Duke of Orleans called to the throne, by
the title of Louis Philippe, King of the French, Belgian and Polish
revolutions.
1831 The cholera appears in Europe. Polish insurrection suppressed, and the
kingdom of Poland incorporated with the Russian empire. London
conferences: Leopold of Saxe-Coburg chosen King of Belgium.
1832 Civil war in Portugal betwixt Pedro and Miguel. The French occupy Ancona,
and lay siege to Antwerp. Parliamentary reform in England.
1833 Meeting of the first reformed Parliament. Abolition of slavery in the British
colonies, with a compensation of £20,000,000 to the slave-owners.
1834 Don Miguel expelled from Portugal. Civil war in Spain. Formation of the
German Zollverein. Accession of Queen Victoria. Buckingham Palace
completed. Insurrection in Upper Canada. A meeting of the Provincial
Convention called at Toronto. Colonel Moodie killed. McKenzie, Van
Egmont and others invest Toronto. Rebels dispersed and leaders flee to
the United States.
1838 Second Insurrection in 1838. In Lower Canada, Mr. and Mrs. Ellice of
Beauharnois, taken prisoners by the rebels at that place and given over
for keeping to the Curé. The Caughnawaga Indians take 64 prisoners
and, tying them with their sashes and garters, send them to Montreal.
Affairs at Napierville and Laprairie. Colonel Prince did, what should have
instantly been done to the Fenian prisoners in the late raid, viz.,
condemned some of the insurgents by drum head Court Martial, and
executed them forthwith. Quiet restored.
1839 Treaty of peace betwixt Holland and Belgium. End of the civil war in Spain.

You might also like