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

Java Coding Problems: Become an expert Java programmer by solving over 200 brand-new, modern, real-world problems, 2nd edition Anghel Leonard download

The document is a promotional overview of the book 'Java Coding Problems, 2nd Edition' by Anghel Leonard, which contains over 200 modern, real-world coding problems aimed at helping readers become expert Java programmers. It includes links to download the book and other related resources, as well as information about the author's background and contributions to the Java community. The book is published by Packt Publishing and covers various advanced topics in Java programming.

Uploaded by

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

Java Coding Problems: Become an expert Java programmer by solving over 200 brand-new, modern, real-world problems, 2nd edition Anghel Leonard download

The document is a promotional overview of the book 'Java Coding Problems, 2nd Edition' by Anghel Leonard, which contains over 200 modern, real-world coding problems aimed at helping readers become expert Java programmers. It includes links to download the book and other related resources, as well as information about the author's background and contributions to the Java community. The book is published by Packt Publishing and covers various advanced topics in Java programming.

Uploaded by

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

Java Coding Problems: Become an expert Java

programmer by solving over 200 brand-new,


modern, real-world problems, 2nd edition Anghel
Leonard pdf download
https://textbookfull.com/product/java-coding-problems-become-an-
expert-java-programmer-by-solving-over-200-brand-new-modern-real-
world-problems-2nd-edition-anghel-leonard/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Java Coding Problems, 2nd Edition: Become an expert


Java programmer by solving over 200 brand-new, modern,
real-world problems Anghel Leonard

https://textbookfull.com/product/java-coding-problems-2nd-
edition-become-an-expert-java-programmer-by-solving-
over-200-brand-new-modern-real-world-problems-anghel-leonard/

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/

Learning Java An Introduction to Real World Programming


with Java Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-
to-real-world-programming-with-java-marc-loy/

Optimization in the Real World Toward Solving Real


World Optimization Problems 1st Edition Katsuki
Fujisawa

https://textbookfull.com/product/optimization-in-the-real-world-
toward-solving-real-world-optimization-problems-1st-edition-
katsuki-fujisawa/
Learning Java An Introduction to Real World Programming
with Java 5th Edition Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-
to-real-world-programming-with-java-5th-edition-marc-loy/

Java Cookbook Problems and Solutions for Java


Developers Early Release Ian F. Darwin

https://textbookfull.com/product/java-cookbook-problems-and-
solutions-for-java-developers-early-release-ian-f-darwin/

Statistics With R Solving Problems Using Real World


Data 1st Edition Jenine K Harris

https://textbookfull.com/product/statistics-with-r-solving-
problems-using-real-world-data-1st-edition-jenine-k-harris/

Java Cookbook Problems and Solutions for Java


Developers final release 4th Edition Ian F. Darwin

https://textbookfull.com/product/java-cookbook-problems-and-
solutions-for-java-developers-final-release-4th-edition-ian-f-
darwin/

Pro Hibernate and MongoDB The Expert s Voice Leonard


Anghel

https://textbookfull.com/product/pro-hibernate-and-mongodb-the-
expert-s-voice-leonard-anghel/
Java Coding Problems
Second Edition

Become an expert Java programmer by solving


over 200 brand-new, modern, real-world
problems

Anghel Leonard

BIRMINGHAM—MUMBAI
Java Coding Problems

Second Edition

Copyright © 2024 Packt Publishing


All rights reserved. No part of this book may be reproduced, stored in
a retrieval system, or transmitted in any form or by any means,
without the prior written permission of the publisher, except in the
case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, the information
contained in this book is sold without warranty, either express or
implied. Neither the author, nor Packt Publishing or its dealers and
distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information
about all of the companies and products mentioned in this book by
the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.

Senior Publishing Product Manager: Denim Pinto

Acquisition Editor – Peer Reviews: Gaurav Gavas

Project Editor: Namrata Katare

Senior Development Editor: Elliot Dallow

Copy Editor: Safis Editing


Technical Editor: Aniket Shetty

Proofreader: Safis Editing

Indexer: Rekha Nair

Presentation Designer: Ajay Patule

Developer Relations Marketing Executive: Vipanshu Parashar

First published: September 2019

Second edition: March 2024

Production reference: 1120324

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83763-394-4

www.packt.com
Contributors

About the author


Anghel Leonard is a chief technology strategist with more than 20
years of experience in the Java ecosystem. In his daily work, he is
focused on architecting and developing Java distributed applications
that empower robust architectures, clean code, and high
performance. He is passionate about coaching, mentoring, and
technical leadership.
He is the author of several books and videos and dozens of articles
related to Java technologies.
About the reviewers
George Adams is a senior software engineer at Microsoft and the
Java Champion and steering committee chair at Eclipse Adoptium.
He was a co-founder of AdoptOpenJDK in 2016 and, since then, has
led its community outreach efforts. He was instrumental in moving
the project to the Eclipse Foundation. George also contributes to both
the Homebrew project and the Node.js Foundation, where he is a
core collaborator and plays an active role in several of the
workgroups.

Ivar Grimstad is a Jakarta EE developer advocate at the Eclipse


Foundation. He is a Java Champion and JUG Leader based in
Sweden. He contributes to the Jakarta EE specifications and is the
PMC Lead for Eclipse Enterprise for Java (EE4J). He is also a
specification lead for Jakarta MVC and represents the Eclipse
Foundation on the JCP Executive Committee. Ivar is also involved in
a wide range of open-source projects and communities and is a
frequent speaker at international developer conferences.
Join our community on Discord
Join our community’s Discord space for discussions with the author
and other readers:
https://discord.gg/8mgytp5DGQ
Contents
Preface
Who this book is for
What this book covers
To get the most out of this book
Get in touch
1. Text Blocks, Locales, Numbers, and Math
Problems
1. Creating a multiline SQL, JSON, and HTML string
Before JDK 8
Starting with JDK 8
Introducing text blocks (JDK 13/15)
Hooking text blocks syntax
2. Exemplifying the usage of text block delimiters
3. Working with indentation in text blocks
Shifting the closing delimiter and/or the content
Using indentation methods
4. Removing incidental white spaces in text blocks
5. Using text blocks just for readability
6. Escaping quotes and line terminators in text blocks
7. Translating escape sequences programmatically
8. Formatting text blocks with variables/expressions
9. Adding comments in text blocks
10. Mixing ordinary string literals with text blocks
11. Mixing regular expression with text blocks
12. Checking if two text blocks are isomorphic
13. Concatenating strings versus StringBuilder
JDK 8
JDK 11
14. Converting int to String
15. Introducing string templates
What’s a string template?
The STR template processor
The FMT template processor
The RAW template processor
16. Writing a custom template processor
17. Creating a Locale
18. Customizing localized date-time formats
19. Restoring Always-Strict Floating-Point semantics
20. Computing mathematical absolute value for int/long
and result overflow
21. Computing the quotient of the arguments and result
overflow
22. Computing the largest/smallest value that is
less/greater than or equal to the algebraic quotient
23. Getting integral and fractional parts from a double
24. Testing if a double number is an integer
25. Hooking Java (un)signed integers in a nutshell
26. Returning the flooring/ceiling modulus
27. Collecting all prime factors of a given number
28. Computing the square root of a number using the
Babylonian method
29. Rounding a float number to specified decimals
30. Clamping a value between min and max
31. Multiply two integers without using loops,
multiplication, bitwise, division, and operators
32. Using TAU
What is TAU?
33. Selecting a pseudo-random number generator
Choosing an algorithm by name
Choosing an algorithm by property
34. Filling a long array with pseudo-random numbers
35. Creating a stream of pseudo-random generators
36. Getting a legacy pseudo-random generator from new
ones of JDK 17
37. Using pseudo-random generators in a thread-safe
fashion (multithreaded environments)
Summary
2. Objects, Immutability, Switch Expressions, and Pattern Matching
Problems
38. Explain and exemplifying UTF-8, UTF-16, and UTF-32
Introducing ASCII encoding scheme (or single-byte
encoding)
Introducing multi-byte encoding
Unicode
Java and Unicode
JDK 18 defaults the charset to UTF-8
39. Checking a sub-range in the range from 0 to length
40. Returning an identity string
41. Hooking unnamed classes and instance main methods
42. Adding code snippets in Java API documentation
Adding attributes
Using markup comments and regions
Highlighting
Linking
Modifying the code’s text
Using external snippets
Regions in external snippets
43. Invoking default methods from Proxy instances
JDK 8
JDK 9+, pre-JDK 16
JDK 16+
44. Converting between bytes and hex-encoded strings
JDK 17+
45. Exemplify the initialization-on-demand holder design
pattern
Static vs. non-static blocks
Nested classes
Tackling the initialization-on-demand holder design
pattern
JDK 16+
46. Adding nested classes in anonymous classes
JDK 16+
47. Exemplify erasure vs. overloading
Erasure in a nutshell
Erasure of generic types
Erasure and bridge methods
Type erasure and heap pollution
Polymorphic overloading in a nutshell
Erasure vs. overloading
48. Xlinting default constructors
49. Working with the receiver parameter
50. Implementing an immutable stack
51. Revealing a common mistake with Strings
52. Using the enhanced NullPointerException
WARNING 1! NPE when calling an instance method via
a null object
WARNING 2! NPE when accessing (or modifying) the
field of a null object
WARNING 3! NPE when null is passed in the method
argument
WARNING 4! NPE when accessing the index value of a
null array/collection
WARNING 5! NPE when accessing a field via a getter
53. Using yield in switch expressions
54. Tackling the case null clause in switch
55. Taking on the hard way to discover equals()
56. Hooking instanceof in a nutshell
57. Introducing pattern matching
The scope of binding variables in pattern matching
Guarded patterns
Type coverage
Current status of pattern matching
58. Introducing type pattern matching for instanceof
59. Handling the scope of a binding variable in type
patterns for instanceof
60. Rewriting equals() via type patterns for instanceof
61. Tackling type patterns for instanceof and generics
62. Tackling type patterns for instanceof and streams
63. Introducing type pattern matching for switch
64. Adding guarded pattern labels in switch
65. Dealing with pattern label dominance in switch
66. Dealing with completeness (type coverage) in pattern
labels for switch
67. Understanding the unconditional patterns and nulls in
switch expressions
Summary
3. Working with Date and Time
Problems
68. Defining a day period
Before JDK 16
JDK 16+
69. Converting between Date and YearMonth
70. Converting between int and YearMonth
71. Converting week/year to Date
72. Checking for a leap year
73. Calculating the quarter of a given date
74. Getting the first and last day of a quarter
75. Extracting the months from a given quarter
76. Computing pregnancy due date
77. Implementing a stopwatch
78. Extracting the count of milliseconds since midnight
79. Splitting a date-time range into equal intervals
80. Explaining the difference between Clock.systemUTC()
and Clock.systemDefaultZone()
81. Displaying the names of the days of the week
82. Getting the first and last day of the year
83. Getting the first and last day of the week
84. Calculating the middle of the month
85. Getting the number of quarters between two dates
86. Converting Calendar to LocalDateTime
87. Getting the number of weeks between two dates
Summary
4. Records and Record Patterns
Problems
88. Declaring a Java record
89. Introducing the canonical and compact constructors for
records
Handling validation
Reassigning components
Defensive copies of the given components
90. Adding more artifacts in a record
91. Iterating what we cannot have in a record
A record cannot extend another class
A record cannot be extended
A record cannot be enriched with instance fields
A record cannot have private canonical constructors
A record cannot have setters
92. Defining multiple constructors in a record
93. Implementing interfaces in records
94. Understanding record serialization
How serialization/deserialization works
Serializing/deserializing gacContainer (a typical Java
class)
Deserializing a malicious stream
Serializing/deserializing gacContainerR (a Java record)
Deserializing a malicious stream
Refactoring legacy serialization
95. Invoking the canonical constructor via reflection
96. Using records in streams
97. Introducing record patterns for instanceof
Nested records and record patterns
98. Introducing record patterns for switch
99. Tackling guarded record patterns
100. Using generic records in record patterns
Type argument inference
Type argument inference and nested records
101. Handling nulls in nested record patterns
102. Simplifying expressions via record patterns
103. Hooking unnamed patterns and variables
Unnamed patterns
Unnamed variables
In a catch block
In a for loop
In an assignment that ignores the result
In try-with-resources
In lambda expressions
104. Tackling records in Spring Boot
Using records in controllers
Using records with templates
Using records for configuration
Record and dependency injection
105. Tackling records in JPA
DTO via record constructor
DTO via record and JPA constructor expression
DTO via record and result transformer
DTO via record and JdbcTemplate
Team up Java records and @Embeddable
106. Tackling records in jOOQ
Summary
5. Arrays, Collections, and Data Structures
Problems
107. Introducing parallel computations with arrays
108. Covering the Vector API’s structure and terminology
The vector element type
The vector shape
The vector species
Vector lanes
Vector operations
Creating vectors
Creating vectors of zeros
Creating vectors of the same primitive value
Creating vectors from Java arrays
Creating vectors from memory segments
109. Summing two arrays via the Vector API
110. Summing two arrays unrolled via the Vector API
111. Benchmarking the Vector API
112. Applying the Vector API to compute FMA
113. Multiplying matrices via the Vector API
114. Hooking the image negative filter with the Vector API
115. Dissecting factory methods for collections
Factory methods for maps
Factory methods for lists
Factory methods for sets
116. Getting a list from a stream
117. Handling map capacity
118. Tackling Sequenced Collections
Applying the Sequenced Collections API to lists
Applying the Sequenced Collections API to
ArrayList and LinkedList
Applying the Sequenced Collections API to sets
Applying the Sequenced Collections API to
HashSet
Applying the Sequenced Collections API to
LinkedHashSet
Applying the Sequenced Collections API to TreeSet
Applying the Sequenced Collections API to maps
Applying the Sequenced Collections API to
LinkedHashMap
Applying the Sequenced Collections API to
SortedMap (TreeMap)
119. Introducing the Rope data structure
Implementing indexAt(Node node, int index)
Implementing concat(Node node1, Node node2)
Implementing insert(Node node, int index, String str)
Implementing delete(Node node, int start, int end)
Implementing split(Node node, int index)
120. Introducing the Skip List data structure
Implementing contains(Integer data)
Implementing insert(Integer data)
Implementing delete(Integer data)
121. Introducing the K-D Tree data structure
Inserting into a K-D Tree
Finding the nearest neighbor
122. Introducing the Zipper data structure
123. Introducing the Binomial Heap data structure
Implementing insert(int key)
Implementing findMin()
Implementing extractMin()
Implementing decreaseKey(int key, int newKey)
Implementing delete(int key)
Implementing unionHeap(BinomialHeap heap)
124. Introducing the Fibonacci Heap data structure
125. Introducing the Pairing Heap data structure
126. Introducing the Huffman Coding data structure
Encoding the string
Decoding the string
127. Introducing the Splay Tree data structure
128. Introducing the Interval Tree data structure
Implementing insert(Interval interval)
129. Introducing the Unrolled Linked List data structure
130. Implementing join algorithms
Nested Loop Join
Hash Join
Sort Merge Join
Summary
6. Java I/O: Context-Specific Deserialization Filters
Problems
131. Serializing objects to byte arrays
132. Serializing objects to strings
133. Serializing objects to XML
134. Introducing JDK 9 deserialization filters
Pattern-based filters
Applying a pattern-based filter per application
Applying a pattern-based filter to all applications in
a process
ObjectInputFilter-based filters
135. Implementing a custom pattern-based
ObjectInputFilter
136. Implementing a custom class ObjectInputFilter
137. Implementing a custom method ObjectInputFilter
138. Implementing a custom lambda ObjectInputFilter
139. Avoiding StackOverflowError at deserialization
140. Avoiding DoS attacks at deserialization
141. Introducing JDK 17 easy filter creation
142. Tackling context-specific deserialization filters
Applying a Filter Factory per application
Applying a Filter Factory to all applications in a process
Applying a Filter Factory via ObjectInputFilter.Config
Implementing a Filter Factory
143. Monitoring deserialization via JFR
Summary
7. Foreign (Function) Memory API
Problems
144. Introducing Java Native Interface (JNI)
Generating the header (.h) file
Implementing the modern_challenge_Main.cpp
Compiling the C source code
Generating the native shared library
Finally, run the code
145. Introducing Java Native Access (JNA)
Implementing the .cpp and .h files
Compiling the C source code
Generating the native shared library
Finally, run the code
146. Introducing Java Native Runtime (JNR)
147. Motivating and introducing Project Panama
148. Introducing Panama’s architecture and terminology
149. Introducing Arena and MemorySegment
Introducing memory layouts (ValueLayout)
Allocating memory segments of value layouts
Setting/getting the content of a memory segment
Working with Java strings
150. Allocating arrays into memory segments
151. Understanding addresses (pointers)
152. Introducing the sequence layout
Introducing PathElement
Introducing VarHandle
Putting PathElement and VarHandle together
Working with nested sequence layouts
153. Shaping C-like structs into memory segments
Introducing StructLayout
154. Shaping C-like unions into memory segments
Introducing UnionLayout
155. Introducing PaddingLayout
Hooking size, alignment, stride, and padding
Hooking size
Hooking alignment
Hooking stride
Hooking padding
Adding implicit extra space (implicit padding) to
validate alignment
Adding explicit extra space (explicit padding) to
validate alignment
156. Copying and slicing memory segments
Copying a segment
Copying a part of the segment into another segment
(1)
Copying a segment into an on-heap array
Copying an on-heap array into a segment
Copying a part of the segment into another segment
(2)
Slicing a segment
Using asOverlappingSlice()
Using segmentOffset()
157. Tackling the slicing allocator
158. Introducing the slice handle
159. Introducing layout flattening
160. Introducing layout reshaping
161. Introducing the layout spreader
162. Introducing the memory segment view VarHandle
163. Streaming memory segments
164. Tackling mapped memory segments
165. Introducing the Foreign Linker API
166. Calling the sumTwoInt() foreign function
167. Calling the modf() foreign function
168. Calling the strcat() foreign function
169. Calling the bsearch() foreign function
170. Introducing Jextract
171. Generating native binding for modf()
Summary
8. Sealed and Hidden Classes
Problems
172. Creating an electrical panel (hierarchy of classes)
173. Closing the electrical panel before JDK 17
Applying the final modifier
Defining package-private constructors
Declaring classes/interfaces as non-public
Throwing everything in a module
Conclusion
174. Introducing JDK 17 sealed classes
175. Introducing the permits clause
Working with sealed classes in separate sources (same
package)
Working with sealed classes in separate packages
176. Closing the electrical panel after JDK 17
177. Combining sealed classes and records
178. Hooking sealed classes and instanceof
179. Hooking sealed classes in switch
180. Reinterpreting the Visitor pattern via sealed classes
and type pattern matching for switch
181. Getting info about sealed classes (using reflection)
182. Listing the top three benefits of sealed classes
183. Briefly introducing hidden classes
184. Creating a hidden class
Summary
9. Functional Style Programming – Extending APIs
Problems
185. Working with mapMulti()
186. Streaming custom code to map
187. Exemplifying a method reference vs. a lamda
Scenario 1: Calling printReset()
Scenario 2: Calling static printNoReset()
Conclusion
188. Hooking lambda laziness via Supplier/Consumer
189. Refactoring code to add lambda laziness
Fixing in imperative fashion
Fixing in functional fashion
190. Writing a Function<String, T> for parsing data
191. Composing predicates in a Stream’s filters
192. Filtering nested collections with Streams
193. Using BiPredicate
194. Building a dynamic predicate for a custom model
195. Building a dynamic predicate from a custom map of
conditions
196. Logging in predicates
197. Extending Stream with containsAll() and containsAny()
Exposing containsAll/Any() via a custom interface
Exposing containsAll/Any() via an extension of Stream
198. Extending Stream with removeAll() and retainAll()
Exposing removeAll()/retainAll() via a custom interface
Exposing removeAll/retainAll() via an extension of
Stream
199. Introducing stream comparators
Sorting via natural order
Reversing the natural order
Sorting and nulls
Writing custom comparators
200. Sorting a map
201. Filtering a map
202. Creating a custom collector via Collector.of()
Writing a custom collector that collects into a TreeSet
Writing a custom collector that collects into a
LinkedHashSet
Writing a custom collector that excludes elements of
another collector
Writing a custom collector that collects elements by
type
Writing a custom collector for SplayTree
203. Throwing checked exceptions from lambdas
204. Implementing distinctBy() for the Stream API
205. Writing a custom collector that takes/skips a given
number of elements
206. Implementing a Function that takes five (or any other
arbitrary number of) arguments
207. Implementing a Consumer that takes five (or any
other arbitrary number of) arguments
208. Partially applying a Function
Summary
10. Concurrency – Virtual Threads and Structured Concurrency
Problems
209. Explaining concurrency vs. parallelism
210. Introducing structured concurrency
211. Introducing virtual threads
What’s the problem with platform (OS) threads?
What are virtual threads?
Creating a virtual thread
How many virtual threads we can start
Backward compatibility
Avoiding fake conclusions (potentially myths)
212. Using the ExecutorService for virtual threads
213. Explaining how virtual threads work
Capturing virtual threads
Pinning virtual threads
214. Hooking virtual threads and sync code
215. Exemplifying thread context switching
Example 1
Example 2
Example 3
216. Introducing the ExecutorService invoke all/any for
virtual threads – part 1
Working with invokeAll()
Working with invokeAny()
217. Introducing the ExecutorService invoke all/any for
virtual threads – part 2
218. Hooking task state
219. Combining newVirtualThreadPerTaskExecutor() and
streams
220. Introducing a scope object (StructuredTaskScope)
ExecutorService vs. StructuredTaskScope
221. Introducing ShutdownOnSuccess
222. Introducing ShutdownOnFailure
223. Combining StructuredTaskScope and streams
224. Observing and monitoring virtual threads
Using JFR
Using Java Management Extensions (JMX)
Running 10,000 tasks via the cached thread pool
executor
Running 10,000 tasks via the fixed thread pool
executor
Running 10,000 tasks via the virtual thread per task
executor
Summary
11. Concurrency ‒ Virtual Threads and Structured Concurrency:
Diving Deeper
Problems
225. Tackling continuations
Introducing continuations
Continuations and virtual threads
226. Tracing virtual thread states and transitions
NEW
STARTED
RUNNING
PARKING
PARKED/PINNED
YIELDING
RUNNABLE
TERMINATED
227. Extending StructuredTaskScope
228. Assembling StructuredTaskScope
229. Assembling StructuredTaskScope instances with
timeout
230. Hooking ThreadLocal and virtual threads
231. Hooking ScopedValue and virtual threads
Thread-local variables’ shortcomings
Introducing scoped values
232. Using ScopedValue and executor services
233. Chaining and rebinding scoped values
Changing scoped values
Rebinding scoped values
234. Using ScopedValue and StructuredTaskScope
235. Using Semaphore instead of Executor
236. Avoiding pinning via locking
237. Solving the producer-consumer problem via virtual
threads
238. Solving the producer-consumer problem via virtual
threads (fixed via Semaphore)
239. Solving the producer-consumer problem via virtual
threads (increase/decrease consumers)
240. Implementing an HTTP web server on top of virtual
threads
241. Hooking CompletableFuture and virtual threads
242. Signaling virtual threads via wait() and notify()
Summary
12. Garbage Collectors and Dynamic CDS Archives
Problems
243. Hooking the garbage collector goal
244. Handling the garbage collector stages
245. Covering some garbage collector terminology
Epoch
Single and multiple passes
Serial and parallel
Stop-the-World (STW) and concurrent
Live set
Allocation rate
NUMA
Region-based
Generational garbage collection
246. Tracing the generational GC process
247. Choosing the correct garbage collector
248. Categorizing garbage collectors
Serial garbage collector
Parallel garbage collector
Garbage-First (G1) collector
Z Garbage Collector (ZGC)
Shenandoah Garbage Collector
Concurrent Mark Sweep (CMS) collector (deprecated)
249. Introducing G1
Design principles
250. Tackling G1 throughput improvements
Delaying the start of the Old generation
Focusing on easy pickings
Improving NUMA-aware memory allocation
Parallelized full-heap collections
Other improvements
251. Tackling G1 latency improvements
Merge parallel phases into a larger one
Reduction of metadata
Better work balancing
Better parallelization
Better reference scanning
Other improvements
252. Tackling G1 footprint improvements
Maintain only the needed metadata
Release memory
253. Introducing ZGC
ZGC is concurrent
ZGC and colored pointers
ZGC and load barriers
ZGC is region-based
254. Monitoring garbage collectors
255. Logging garbage collectors
256. Tuning garbage collectors
How to tune
Tuning the serial garbage collector
Tunning the parallel garbage collector
Tuning the G1 garbage collector
Tuning Z Garbage Collector
Tuning Metaspace (Metadata space)
257. Introducing Application Class Data Sharing (AppCDS,
or Java’s Startup Booster)
Tackling a JDK class data archive
JDK 10/JDK 11
JDK 12+
Tackling application class data archive
Before JDK 13
JDK 13+
JDK 19+
Summary
13. Socket API and Simple Web Server
Problems
258. Introducing socket basics
259. Introducing TCP server/client applications
Blocking vs. non-blocking mechanisms
260. Introducing the Java Socket API
Introducing NetworkChannel
Tackling socket options
261. Writing a blocking TCP server/client application
Writing a single-thread blocking TCP echo server
Creating a new server socket channel
Configuring the blocking mechanism
Setting server socket channel options
Binding the server socket channel
Accepting connections
Transmitting data over a connection
Closing the channel
Putting it all together into the echo server
Writing a single-thread blocking TCP client
Creating a new (client) socket channel
Configuring the blocking mechanism
Setting client socket channel options
Connecting the client socket channel
Transmitting data over a connection
Closing the channel
Putting it all together into the client
Testing the blocking echo application
262. Writing a non-blocking TCP server/client application
Using the SelectionKey class
Using the Selector methods
Writing the non-blocking server
Writing the non-blocking client
Testing the non-blocking echo application
263. Writing UDP server/client applications
Writing a single-thread blocking UDP echo server
Creating a server datagram-oriented socket
channel
Setting datagram-oriented socket channel options
Binding the server datagram-oriented socket
channel
Transmitting data packets
Closing the channel
Putting it all together into the client
Writing a connectionless UDP client
Testing the UDP connectionless echo application
Writing a connected UDP client
264. Introducing multicasting
A brief overview of MembershipKey
265. Exploring network interfaces
266. Writing a UDP multicast server/client application
Writing a UDP multicast server
Writing a UDP multicast client
Blocking/unblocking datagrams
Testing the multicasting server/client application
267. Adding KEM to a TCP server/client application
Generating a public-private keypair by the receiver
Transmitting the public key to the sender
Generating the common secret key by the sender
Sending the encapsulation message to the receiver
Using the secret key to encrypt/decrypt messages
268. Reimplementing the legacy Socket API
269. Quick overview of SWS
Key abstractions of SWS
270. Exploring the SWS command-line tool
Starting SWS from the command line
Configuring SWS from the command line
Stopping SWS from the command line
271. Introducing the com.sun.net.httpserver API
Using a custom HttpHandler
Using a custom filter
Using a custom executor
272. Adapting request/exchange
273. Complementing a conditional HttpHandler with
another handler
274. Implementing SWS for an in-memory file system
275. Implementing SWS for a zip file system
276. Implementing SWS for a Java runtime directory
Summary
Other Books You May Enjoy
Index
Preface

The super-fast evolution of the JDK between versions 12 and 21


means two things: first, Java now has a host of powerful new
features that you can adopt to solve a variety of modern-day
problems; second, the learning curve of modern Java is becoming
very steep.
This book enables you to take an objective approach to solving
common problems by explaining the correct practices and decisions
you need to make with respect to complexity, performance,
readability, and more.

Java Coding Problems, Second Edition, will help you complete your
daily tasks and meet deadlines, all while becoming a more proficient
and self-sufficient Java developer. You can count on the 270+ (all
brand-new for this edition) problems in this book to cover the most
common and fundamental areas of interest: strings, numbers, arrays,
collections, the Foreign Function and Memory API, data structures,
date and time, pattern matching, sealed/hidden classes, functional
programming, virtual threads, Structured Concurrency, Garbage
Collectors, Dynamic CDS Archives, the Socket API, and Simple Web
Server.
Put your skills on steroids with problems that have been carefully
crafted to highlight and teach the core knowledge needed for daily
work. In other words (no matter if your task is simple, middling, or
complex), having this knowledge in your tool belt is a must, not an
option.

By the end of this book, you will have gained a strong


understanding of Java concepts, and you’ll have the confidence to
develop and choose the right solutions to all your Java problems.
While this book is entirely stand-alone, and you do not need
anything else to get the most out of it, many of the topics covered in
this book are also explored in Java Coding Problems, First Edition. If
you haven’t already read it, and you wish to get even more practice
in, then consider picking that book up for a completely different set
of Java problems.
Random documents with unrelated
content Scribd suggests to you:
"I believe I never answered your question who it was that advised me to retire from
Parliament. I entirely forget. Your question, Will there be war? I answer, I know no more
than you do, but I am inclined to believe the French will attack Spain, very unadvisedly in
my opinion, and I shall be surprised if the French Government itself, however priding
itself on its policy, will not ultimately have reason to form the same judgment.... Never
was there before a country on earth, the public affairs of which (for many years past at
least I may affirm it,) were administered with such a simple and strong desire to promote
the public welfare as those of Great Britain. And it is very remarkable that some of those
very measures which were brought forward and carried through with the most general
concurrence have subsequently appeared most doubtful. The present extreme distress of
the agricultural class throughout the whole kingdom, is admitted by all to have been in
some degree, by many to have been entirely, caused by our ill-managed if not ill-advised
return to cash payments, in which nearly the whole of both Houses concurred. Surely this
should teach us to be diffident in our judgments of others, and to hold our own opinions
with moderation. In short, my dear Samuel, the best preparation for being a good
politician, as well as a superior man in every other line, is to be a truly religious man. For
this includes in it all those qualities which fit men to pass through life with benefit to
others and with reputation to ourselves. Whatever is to be the effect produced by the
subordinate machinery, the main-spring must be the desire to please God, which, in a
Christian, implies faith in Christ and a grateful sense of the mercies of God through a
Redeemer, and an aspiration after increasing holiness of heart and life. And I am
reminded (you will soon see the connection of my ideas) of a passage in a former letter
of yours about a home, and I do not deny that your remarks were very natural. Yet every
human situation has its advantages as well as its evils. And if the want of a home deprive
us of the many and great pleasures which arise out of the relations and associations,
especially in the case of a large family, with which it is connected, yet there is an
advantage, and of a very high order, in our not having this well-known anchoring ground,
if I may so term it. We are less likely to lose the consciousness of our true condition in
this life; less likely to forget that while sailing in the ocean of life we are always exposed
to the buffeting of the billows, nay, more, to the rock and the quicksand. The very feeling
of desolateness of which you speak—for I do not deny having formerly experienced some
sensations of this kind, chiefly when I used to be long an inmate of the houses of friends
who had wives and families to welcome them home again after a temporary absence—
this very feeling led me, and taught me in some measure habitually to look upwards to
my permanent and never failing inheritance, and to feel that I was to consider myself
here as a pilgrim and a stranger who had no continuing city but who sought one to
come. Yet this very conviction is by no means incompatible with the attachment and
enjoyment of home-born pleasures, which doubtless are natural and virtuous pleasures,
such as it gratifies me and fills me with hope to see that my very dear Sam relishes with
such vivid delight and that he looks forward to them with such grateful anticipations.
"I have not time now to explain to you, as otherwise I would, how it happened that I do
not possess a country house. But I may state to you in general, that it arose from my not
having a large fortune, compared, I mean, with my situation, and from the peculiar
duties and circumstances of my life."
"March 23, 1823.
"Above all remember the one thing needful. I had far rather that you should be a true
Christian than a learned man, but I wish you to become the latter through the influence
of the former. I had far rather see you unlearned than learned from the impulse of the
love of human estimation as your main principle."
On the 15th of May Mr. F. Buxton moved this resolution in the House of Commons: "That
the state of slavery is repugnant to the principles of the British Constitution and of the
Christian Religion, and that it ought to be abolished gradually throughout the British
Colonies with as much expedition as may be found consistent with a due regard to the
well-being of the parties concerned." The main point was that all negro children born
after a certain day were to be free.
"May 17, 1823.
"The debate was by no means so interesting as we expected. Buxton's opening speech
was not so good as his openings have before been. His reply however, though short, was,
not sweet indeed, but excellent. I was myself placed in very embarrassing circumstances
from having at once to decide, without consulting my friends, on Mr. Canning's offers, if I
may so term them. However, I thank God, I judged rightly, that it would not be wise to
press for more on that night, as subsequent conversation with our friends rendered
indubitably clear; and on the whole we have done good service, I trust, by getting Mr.
Canning pledged to certain important reforms. I should speak of our gain in still stronger
terms but for his (Canning's) chief friend being a West Indian, Mr. Charles Ellis, a very
gentlemanly, humane man, but by no means free from the prejudices of his caste.
"Dear Robert has just been prevailed on by William's kind importunity to try to study for a
while at Brompton Grove. I am glad of it on all accounts. It would add substantially to the
pleasures of my life, if my dear boys could acquire firmness enough to study at home. I
would do my best to promote the success of the experiment; but, believe me, it is a sad
habit that of being able to study only when you have 'all appliances and means to boot.'
"I just recollect this letter will reach you on the Sunday. Allow me, therefore, to repeat
my emphatic valediction Remember. You will be in my heart and in my prayers, and
probably we shall be celebrating about the same time the memorial of our blessed Lord's
suffering and the bond of the mutual affection of His disciples towards each other. The
anniversaries which have passed remind me forcibly of the rapid flight of time. My course
must be nearly run, though perhaps it may please that God who has hitherto caused
goodness and mercy to follow me all my days, to allow me to see my dear boys entered
into the exercise of their several professions, if they are several. But how glad shall I be if
they all can conscientiously enter into the ministry, that most useful and most honourable
of all human employments."[50]
"June 14.
"All may be done through prayer—almighty prayer, I am ready to say; and why not? for
that it is almighty is only through the gracious ordination of the God of love and truth. Oh
then, pray, pray, pray, my dearest boy. But then remember to estimate your state on self-
examination not by your prayers, but by what you find to be the effects of them on your
character, tempers, and life."
"July 12, 1823.
"It has often been a matter of grief to me that both Henry and Robert have a sad habit of
appearing, if not of being, inattentive at church. The former I have known turn half or
even quite round and stare (I use the word designedly) into the opposite pew. I am not
aware whether you have the same disposition (real or apparent) to inattention at public
worship. I trust I need not endeavour to enforce on you that it is a practice to be
watched against with the utmost care. It is not only a crime in ourselves, but it is a great
stumbling-block of offence to others. The late Mr. Scott, though an excellent man, had
contracted a habit of staring in general while reading the prayers of our excellent liturgy;
and he once told me himself he actually did it most, when his mind was most intent on
the solemn service he was performing. But to others he appeared looking at the
congregation, especially at any persons entering the chapel, and many I fear were
encouraged to a degree of distraction and inattention in prayer by the unseemly habit he
had contracted. Now let me entreat you, my dearest boy, to watch against every
approach to inattention in yourself, and to help dear Henry, in whom I have remarked the
practice, to get the better of it. I have always found it a great aid in keeping my thoughts
from wandering at church to repeat the prayers to myself, either in a whisper or mentally,
as the minister has being going along, and I highly approve of making responses, and
always when you were children tried to have you make them; but I used to think your
mother did not join me in this when you were next to her, partly probably from her own
mind being more closely engaged in the service—prayer being the grand means of
maintaining our communication with heaven, and the life of religion in the soul claiming
all possible attention."
In the next letter Wilberforce mentions that he had limited his personal expenditure so as
to have larger sums to give away. He says that he had left off giving claret, then a costly
wine, and some other expensive articles still exhibited by those of his rank. He speaks
strongly against gratifying all the cravings of fashion, thoughtlessness, or caprice.
"Barmouth, October 14, 1823.
"My very dear Samuel,—I again take up my pen to give you my sentiments on the
important subject on which I promised to write to you, and on which you have kindly
asked my advice. But before I proceed to fulfil this engagement let me mention what I
had intended to state in my last, but omitted, that I have reason to believe dear Robert
has suffered in the estimation of some of my friends, whether rightly or wrongly I really
know not, from the idea that his associates were not religious men (irreligious in its
common acceptation would convey more than I mean), and therefore that he preferred
that class of companions. Now when people have once conceived anything of a prejudice
against another, on whatever grounds, they are disposed to view all he says and does
with different eyes, and to draw from it different conclusions from those which would
otherwise have been produced, and I suspect dear Robert has suffered unjustly in this
way. However, he will, I doubt not, live through it, and so long as all is really right, I care
less for such temporary misconceptions, though, by the way, they may be very injurious
to the temporal interests, and to the acceptance of the subject of them.
"But now let me state to you my sentiments concerning your principles and conduct as to
society, and first I must say that if I were in your case I should be very slow in forming
new acquaintances. Having already such good companions in Robert, Sir G. Prevost, and
I hope Ryder, it would surely be wise to be satisfied with them at the first, unless there
were any in whose instance I was sure I was on safe and good ground. But now to your
question itself. There are two points of view in which this subject of good associates must
naturally be regarded. The one in that which is the ordinary object of social intercourse,
that I mean of recreation: for it certainly is one of the very best recreations, and may be
rendered indeed not merely such, but conducive to higher and better ends. On this first
head, however, I trust I need say nothing in your case, I will therefore pass it by for the
present. It would, I am persuaded, be no recreation to you to be in a party which should
be disgraced by obscenity or profaneness. But the second view is that which most
belongs to our present inquiry—that, I mean, of the society in which it may appear
necessary to take a share on grounds of conformity (where there is nothing wrong) to
the ordinary customs of life, and even on the principle of 'providing things honest in the
sight of all men' (honest in the Greek is δἱκαιοϛ) and not suffering your good to be evil
spoken of. Now in considering this question, I am persuaded I need not begin in my dear
Samuel's instance with arguing for, but may assume the principle that there are no
indifferent actions properly speaking, I should rather say none with which religion has
nothing to do. This however is the commonly received doctrine of those who consider
themselves as very good Christians. Just as in Law it is an axiom, 'De minimis non curat
lex.' On the contrary, a true Christian holds, in obedience to the injunction, 'Whatever you
do in word or deed' that the desire to please his God and Saviour must be universal. It is
thus that the habit of living in Christ, and to Christ is to be formed. And the difference
between real and nominal Christians is more manifest on small occasions than on greater.
In the latter all who do not disclaim the authority of Christ's commands must obey them,
but in the former only they will apply them who do make religion their grand business,
and pleasing their God and Saviour, and pleasing, instead of grieving the Spirit, their
continual and habitual aim. We are therefore to decide the question of the company you
should keep on Scriptural principles, and the principle I lately quoted 'Provide things
honest,' &c. (There are several others of a like import, and I think they are not always
sufficiently borne in mind by really good people, this of course forbids all needless
singularities, &c.) That principle must doubtless be kept in view. But again, you will not
require me to prove that it can only have any jurisdiction where there is nothing wrong to
be participated in or encouraged. And therefore I am sure you will not deny that you
ought not to make a part of any society in which you will be hearing what is indecent or
profane. I hope that there are not many of the Oriel undergraduates from whom you
would be likely to hear obscenity or profaneness, and I trust that you will not knowingly
visit any such. As to the wine parties, if I have a correct idea of them they are the young
men going after dinner to each other's rooms to drink their wine, eat their fruit, &c.; and
with the qualification above specified, I see no reason for your absenting yourself from
them, if your so doing would fairly subject you to the charge of moroseness or any other
evil imputation. I understand there is no excess, and that you separate after a short time.
Its being more agreeable to you to stay away I should not deem a legitimate motive if
alone. But in all these questions the practical question often is, how the expenditure of
any given amount of time and money (for the former I estimate full as highly as the
latter) can be made productive of the best effect. There is one particular member of your
college with whom I hope you will form no acquaintance. Would it make it more easy for
you to avoid this, if you were able to allege that I had exacted from you a promise to that
effect? It was not from Robert, but from another person, that I heard of him a particular
instance of misconduct, which I believe even in the more relaxed discipline of Cambridge
would have drawn on the offender exemplary punishment. Such a man must, I am sure,
be a very dangerous companion. If it be necessary for you to know him, of course you
will treat him like a gentleman; but further than this I hope you will not go. From what
Robert said to me I have a notion that there is a very foolish practice, to call it by the
softest name, of spending considerable sums in the fruit and wine of these wine
drinkings, where I understood that there was no excess, every man also being allowed to
please himself as to the wine he drinks. But for a young man, the son perhaps of a
clergyman who is straining to the utmost to maintain him at college, stinting himself, his
wife and daughters in comforts necessary to their health, for such a young man to be
giving claret and buying expensive fruit for his young companions is absolutely criminal.
And what is more, I will say that young men are much altered if any youth of spirit who
should frankly declare, 'My father cannot afford such expensive indulgences, and I will
not deprive him or my brothers and sisters for my own gratification,' would not be
respected for his manliness and right feeling. Your situation is different, though, by the
way, your father has left off giving claret except in some very special cases, and has
entirely left off several other expensive articles, which are still exhibited by others of his
rank. But then I know this will not commonly be imputed to improper parsimony in me.
And if you or any other Oxonian could lighten the pressure on young men going to
college, you would be rendering a highly valuable service to the community, besides the
too little considered obligation of limiting our own expenditure for our own indulgence as
much as we can, consistently with 'good report,' and with not suffering our good to be
evil spoken of. I say this deliberately, that it is a duty not sufficiently borne in mind even
by real Christians, when we read the strong passage in the 15th of Deuteronomy, and still
more when we remember our Saviour's language in the 25th of St. Matthew, we shall see
reason to be astonished that the generality of those who do fear God, and mean in the
main to please Him, can give away so small a proportion of their fortunes, and so little
appear sensible of the obligation under which they lie to economise as much as they can
for the purpose of having the funds for giving away within their power. We serve a kind
Master, who will even accept the will for the deed when the deed was not in our power.
But this will not be held to be the case when we can gratify all the cravings of fashion
and self-indulgence, or even thoughtlessness or caprice. What pleasure will a true
Christian sometimes feel in sparing himself some article which he would be glad to
possess, and putting the price instead into his charity purse, looking up to his Saviour
and in heart offering it up to His use. Oh, my very dear Samuel, be not satisfied with the
name of Christian. But strive to be a Christian 'in life and in power and in the Holy Ghost.'
I think a solitary walk or ride now and then would afford an excellent opportunity for
cultivating spirituality of mind, the grand characteristic of the thriving Christian.
"But my feelings draw me off from the proper subject I was writing upon—expense. And
really, when I consider it merely in the view of the misery that may be alleviated, and the
tears that may be wiped away by a very little money judiciously employed, I grow
ashamed of myself for not practising more self-denial that I may apply my savings to
such a purpose. Then think of the benefits to be rendered to mankind by missionary
societies. Besides all this, I really believe there is commonly a special blessing on the
liberal, even in this life, and on their children; and I hesitate not to say to you that, as
you will, I hope, possess from me what, with the ordinary emoluments of a profession,
may afford you a comfortable competence, I am persuaded I shall leave you far more
likely to be happy than if you were to have inherited from me £10,000 more (and I say
the same for your brothers also), the fruits of my bachelor savings. In truth, it would be
so if the Word of God be true, for it is full of declarations to that effect. Now all this is
general doctrine. I am aware of it. I can only give you principles here. It must be for you
to apply them, and if you apply them with simplicity of intention, all, I doubt not, will be
well. But again I cannot help intimating my persuasion that you would do well to confine
yourself at first to the few friends you already have and on whom you can depend. And
also let me suggest that it would be truly wise to be looking around you, and if you
should see anyone whose principles, and character, and manners are such as suggest the
hope that he might be desirable even for a friend, then to cultivate his acquaintance. May
our Heavenly Father direct and prosper you, carry you safely through the ordeal into
which you are just about to enter, and at length receive you into that blessed world
where danger will be over, and all will be love and peace and joy for evermore.
"I am ever affectionately yours,

"W. Wilberforce."
"November 5, 1823.
"I trust I scarcely need assure you that I must always wish to make you comfortable
quoad money matters, and on the other hand that the less the cost of rendering you so,
the more convenient to me. My income is much diminished within the last few years,
while the expenses of my family have greatly increased....
"What a comfort it is to know that our Heavenly Father is ever ready to receive all who
call upon Him. He delighteth in mercy, and ever remember that as you have heard me
say, mercy is kindness to the guilty, to those who deserve punishment. What a delightful
consideration it is that our Saviour loves His people better than we love each other, than
an earthly parent loves his child."
"November 7, 1823.
"There is a vile and base sentiment current among men of the world that, if you want to
preserve a friend you must guard against having any pecuniary transactions with him.
But it is a caution altogether unworthy of a Christian bosom. It is bottomed in the
mistakenly supposed superior value of money to every other object, and in a very low
estimate of human friendship. I hope I do not undervalue my money, but I prize my time
at a still higher rate, and have no fear that any money transaction can ever lessen the
mutual confidence and affection which subsists between us and which I trust will never
be diminished. And let me take this opportunity also of stating that you would give me
real pleasure by making me your friend and opening your heart to me as much in every
other particular. I trust you would never find me abusing your confidence. Even any
indiscretions or faults, if there should be any, if I can help to prevent your being involved
in difficulties by them. But I hate to put such a case. It is no more than what is due to
my dear Samuel, to say that my anticipations are of a very different sort. And I can truly
declare that the good conduct and kindness of my children towards me is a source of the
purest and greatest pleasure I do or can enjoy."[51]
"August 6, 1824.
"I can bear silence no longer, and I beg you will in future send me or your dear mother a
something, be it ever so short, in the way of a letter once a week, if it be merely a
certificate of your existence. I have been for some days thinking of writing to you, in
consequence of my having heard that your friend Ryder and Sir George Prevost were
reading classics with Mr. Keble. Could you not have been allowed to make it a
triumvirate? Much as I value classical scholarship, I prize still more highly the superior
benefit to be derived from associating with such good young men as I trust the two
gentlemen are whose names I have mentioned, and I have the satisfaction of knowing
that you have the privilege of calling them your friends. Is it yet too late?"
"September 10, 1824.
"As I was talking to your mother this morning on money matters it shot across my mind
that you had desired me to send you a supply, which I had neglected to do. I am truly
sorry for my inadvertency, and will send you the half of a £20 bank note which I happen
to possess, the other half following of course to-morrow. Ask for what you want, and we
will settle when you are here. It gives me real pleasure to believe that you are
economical on principle, and it is only by being so that one can be duly liberal. Without
self-denial every man, be his fortune what it may, will find himself unable to act as he
ought in this particular, not that giving is always the best charity, far from it; employing
people is often a far preferable mode of serving them. To you I may say that if I have
been able to be liberal not less before my marriage than after it, it was from denying
myself many articles which persons in my own rank of life and pecuniary circumstances
almost universally indulged in. Now when I find my income considerably decreased on
the one hand, and my expenses (from my four sons) greatly increased on the other,
economy must even be made parsimony, which, justly construed, does not in my
meaning at all exclude generosity."
This letter is here interrupted, he says, by "two young widows—both of whom had
recently lost their husbands in India—with their four little children, all in deep mourning.
Yet the two widows have the best of all supports in the assured persuasion that their
husbands were truly pious, and in the hope that they themselves are so."
It is easy to imagine the reception given to the "two young widows" by Wilberforce. He
had not yet learned the lesson of "economy or even parsimony" as regarded his charities
—even when he had to reduce his expenses he spent £3,000[52] in one year on charity.
"December 10, 1824.
"I have deemed it quite a duty on this delicious day to prolong my country walk in a tête-
à-tête with your dear mother, a tête-à-tête, however, from which our dear children's
images are not excluded. I own that those who are termed Methodists by the world do
give more liberally to the distressed than others, yet that I think they do not in this duty
come up to the full demands of Scripture. The great mistake that prevails as I conceive
is, it's being thought right that all persons who are received on the footing of gentlemen
are to live alike. And without economy there cannot be sufficient liberality. I can sincerely
declare that my wish that my sons should be economical, which is quite consistent with
being generous, nay, as I said before, is even necessary to it, arises far more from my
conviction of the effects of economical habits on their minds and happiness in future life,
than on account of the money that will be thereby saved. You have heard me, I doubt
not, praise Paley's excellent remark on the degree in which a right constitution of the
habits tends to produce happiness, and you may proceed with the train of ideas I have
called up in your mind."
"October 26, 1825.
"You ask me about your Uncle Stephen's having been a newspaper reporter. He was. The
case was this. At the age of, I believe, eighteen, he came up to town to study the law,
when the sudden death of his father not only stopped his supplies, but threw on his
hands the junior branches of the family, more especially three or four sisters. Seeing no
other resource, he embraced an offer, made to him I believe through or by Mr.
Richardson, the friend of poor Sheridan. Richardson afterwards came into Parliament,
and the fact respecting Stephen came out thus, a few years ago. A regulation was
proposed by some of the benchers of Lincoln's Inn that no one should be permitted to be
called to the Bar who ever had practised the reporting art. Sheridan brought the question
forward in the House of Commons. Stephen, who was then in Parliament, spoke to the
question, and in arguing against the illiberal and even cruel severity of the regulation, put
a supposed case, that the son of a gentleman, by a father's sudden death was at once
deprived of the means of pursuing the legal profession on which he was just entering,
being also harassed in his mind by the distressed state of some affectionate sisters. Thus
embarrassed, he received an offer of employment as a reporter, and gladly accepted it
and discharged its duties, thereby being enabled to prosecute his professional studies as
well as to assist his relatives. 'But,' added Stephen, 'the case I have just stated is no
imaginary one. It is the story of a living individual. It is that, sir, of the individual who has
now the honour to address you.' There is in all bodies of Englishmen a generous feeling
which is always called forth powerfully when a man confesses, or rather boldly avows any
circumstance respecting himself which, according to the false estimate of the world,
might be supposed to disparage him; as when Peel at the meeting for a monument to
James Watt declared that, 'owing all his prosperity to the successful industry of a person
originally in the humble walks of life,' the applause was overpowering. And I never
remember a more general or louder acclamation than immediately broke out when
Stephen had (indeed before he had completely) closed his declaration."
"December 16, 1825.
"It is Henry Thornton[53] that was connected with the house of Pole & Co. He became a
partner about five months ago. The storm through which he has been passing has been
indeed violent; but the call for self-possession, temper, judgment, and above all
scrupulous, punctilious integrity has been abundantly answered. He has behaved so as to
draw on him the universal applause of all who have witnessed his conduct. Mr. Jno. Smith
especially speaks of it in the highest terms, and has been acting towards him with
corresponding generosity and kindness. It has been very strikingly evidenced that
commercial transactions on a great scale enlarge the mind, and the obedience which,
with men of real principle, is paid to the point of mercantile honour, produces a habit of
prompt, decisive integrity in circumstances of embarrassment and distress. I am happy to
be able to tell you that there is reason to believe that while Henry will gain great credit
he will lose no money. He has borne the trial with the calmness of a veteran."
"Sunday, January 22, 1826.
"You may have heard me mention, that when in my solitary bachelor state I was alone all
day on the Sunday, I used after dinner to call up before me the images of my friends and
acquaintances, and to consider how I could benefit or gratify them. And when the mind is
scarcely awake, or, at least, active enough for any superior purpose, this is no bad
employment for a part of the day, especially if practised with religious associations and
purposes. The day is so raw here that I have yielded to your mother's kind entreaties
that I would not go to church, where the greater part of the family now is at afternoon
service. So I am glad to spend a part of my day with my dearest Samuel.
"I will remind you of an idea which I threw out on the day preceding your departure—
that I feared I had scarcely enough endeavoured to impress on my children the idea that
they must as Christians be a peculiar people. I am persuaded that you cannot
misunderstand me to mean that I wish you to affect singularity in indifferent matters.
The very contrary is our duty. But from that very circumstance of its being right that we
should be like the rest of the world in exterior, manners, &c., &c., results an
augmentation of the danger of our not maintaining that diversity, nay, that contrast,
which the Eye of God ought to see in us to the worldly way of thinking and feeling on all
the various occasions of life, and in relation to its various interests. The man of the world
considers religion as having nothing to do with 99-100ths of the affairs of life, considering
it as a medicine and not as his food, least of all as his refreshment and cordial. He
naturally takes no more of it than his health requires. How opposite this to the apostle's
admonition, 'Whatever ye do in word or deed, do all in the name of the Lord Jesus,
giving thanks to God the Father through Him.' This is being spiritually-minded, and being
so is truly declared to be life and peace. By the way, if you do not possess that
duodecimo volume, 'Owen on Spiritual Mindedness,' let me beg you to get and read it
carefully. There are some obscure and mystic passages, but much that I think is likely to
be eminently useful; and may our Heavenly Father bless to you the perusal of it...."
"February 27, 1826.
"Let me assure you that you give me great pleasure by telling me unreservedly any
doubts you may entertain of the propriety of my principles or conduct. I love your
considering and treating me as a friend, and I trust you will never have reason to regret
your having so done, either in relation to your benefit or your comfort. In stating my
suspicions that I had not sufficiently endeavoured to impress on my children, and that
you were scarcely enough aware of the force of the dictum that Christians were to be a
peculiar people, I scarcely need assure you that I think the commands, 'Provide things
honest in the sight of all men, whatever things are lovely, whatsoever of good report,' &c.
(admirably illustrated and enforced by St. Paul's account of his own principles of
becoming all things to all men), clearly prove that so far from being needlessly singular,
we never ought to be so, but for some special and good reason. Again, I am aware of
what you suggest that, in our days, in which the number of those who profess a stricter
kind of religion than the world of soi-disant Christians in general, there is danger lest a
party spirit should creep in with its usual effects and evils. Against this, therefore, we
should be on the watch. And yet, though not enlisting ourselves in a party, we ought, as I
think you will admit, to assign considerable weight to any opinions or practices which
have been sanctioned by the authority of good men in general. As again, you will I think
admit, that in any case in which the more advanced Christians and the less advanced are
both affected, the former and their interests deserve more of our consideration than the
latter. For instance, it is alleged in behalf of certain worldly compliances, that by making
them you will give a favourable idea, produce a pleasing impression of your religious
principles, and dispose people the rather to adopt them. But then, if you thereby are
likely to become an offence (in the Scripture sense) to weaker Christians, (persons, with
all their infirmities, eminently dear to Christ,) you may do more harm than good, and that
to the class which had the stronger claim to your kind offices. Let my dear Samuel think
over the topic to which I was about next to proceed. I mean our Saviour's language to
the Laodicean Church expressing His abhorrence and disgust at lukewarmness, and the
danger of damping the religious affections by such recreations as He had in mind. Of
course I don't object to domestic dances. It is not the act, the saltus, but the whole tone
of an assembly."
"Clifton, May 27, 1826.
"I am very glad to think that you will be with us. Your dear mother's spirits are not
always the most buoyant, and, coming first to reside in a large, new house without
having some of her children around her, would be very likely to infuse a secret
melancholy which might sadden the whole scene, and even produce, by permanent
association, a lasting impression of despondency. I finish this letter after hearing an
excellent sermon from Robert Hall. It was not merely an exhibition of powerful intellect,
but of fervent and feeling piety, especially impressing on his hearers to live by the faith of
the love of Christ daily, habitually looking to Him in all His characters. Prayer, prayer, my
dear Samuel; let your religion consist much in prayer. May you be enabled more and
more to walk by faith and not by sight, to feel habitually as well as to recognise in all
your more deliberate calculations and plans, that the things that are seen are temporal,
but the things that are not seen are eternal. Then you will live above the world, as one
who is waiting for the coming of the Lord Jesus Christ."[54]
"April 20, 1826.
"I would gladly fill my sheet, yet I can prescribe what may do almost as well. Shut your
door and muse until you fancy me by your side, and then think what I should say to you,
which I dare say your own mind would supply."
"September 30.
"I am thankful to reflect that at the very moment I am now thinking of you and
addressing you; you also are probably engaged in some religious exercise, solitary or
social (for I was much gratified by learning from a passage in one of your letters to your
mother that you and Anderson went through the service of our beautiful liturgy
together). Perhaps you are thinking of your poor old father, and, my dear boy, I hope you
often pray for me, and I beg you will continue to do so.
"I am not sure whether or not I told you of our having been for a week at Lea,[55] having
been detained there by my being slightly indisposed. But it was worth while to be so, if it
were only to witness, or rather to experience, Lady Anderson's exceeding kindness. I
really do not recollect having ever before known such high merits and accomplishments—
the pencil and music combined with such unpretending humility, such true simplicity and
benevolence. With these last Sir Charles is also eminently endowed. He reads his family
prayers with great feeling, and especially with a reverence which is always particularly
pleasing to me. There is, in 'Jonathan Edwards on the Religious Affections,' a book from
which you will, I think, gain much useful matter, a very striking passage, in which he
condemns with great severity, but not at all too great, me judice, that familiarity with the
Supreme King which was affected by some of the religionists of his day, as well as by Dr.
Hawker recently, and remarks very truly that Moses and Elijah, and Abraham the friend of
God (and all of them honoured by such especial marks of the Divine condescension),
always manifested a holy awe and reverence when in the Divine presence."
Samuel Wilberforce had written to his father asking him what advice he should give to a
friend whose family was very irreligious. In the house of this friend 'it was a common
phrase accompanying a shake of each other's hands on meeting, "May we meet together
in hell."' The answer to the appeal for advice is as follows:—
"July 28, 1826.
"I will frankly confess to you that the clearness and strength of the command of the
apostle, 'Children, obey your parents in all things' (though in one passage it is added, 'in
the Lord') weighed so strongly with me as to lead me, at first, to doubt whether or not it
did not overbalance all opposing considerations and injunctions, yet more reflection has
brought me to the conclusion, to which almost all those whom I consulted came still
more promptly, that it is the duty of your young friend to resist his parents' injunction to
go to the play or the opera. That they are quite hotbeds of vice no one, I think, can deny,
for much more might be said against them than is contained in my 'Practical View,'
though I own the considerations there stated appear to my understanding such as must
to anyone who means to act on Christian principles be perfectly decisive. One argument
against the young man's giving up the point in these instances, which has great weight
with me, is this, that he must either give himself entirely up to his friends and suffer
them at least to dictate to him his course of conduct, or make a stand somewhere. Now I
know not what ground he will be likely to find so strong as this must be confessed to be,
by all who will argue the question with him on Scriptural principles, and more especially
on those I have suggested in my 'Practical View' of the love of God, and I might have
added, that of the apostle's injunction, 'Whatever ye do in word or deed, do all in the
name of the Lord Jesus, giving thanks to God and the Father through Him.' I scarcely
need remark that the refusal should be rendered as unobjectionable as possible by the
modest and affectionate manner of urging it, and by endeavouring to render the whole
conduct and demeanour doubly kind and assiduous. I well remember that when first it
pleased God to touch my heart, now rather above forty years ago, it had been reported
of me that I was deranged, and various other rumours were propagated to my
disadvantage. It was under the cloud of these prejudices that I presented myself to some
old friends, and spent some time with them (after the close of the session) at
Scarborough. I conversed and behaved in the spirit above recommended, and I was
careful to embrace any little opportunity of pleasing them (little presents often have no
small effects), and I endeavoured to impress them with a persuasion that I was not less
happy than before. The consequence was all I could desire, and I well recollect that the
late Mrs. Henry Thornton's mother, a woman of very superior powers and of great
influence in our social circle, one day broke out to my mother—she afterwards said to me
something of the same kind, not without tears—'Well, I can only say if he is deranged I
hope we all shall become so.' To your young friend again I need not suggest the duty of
constant prayer for his nearest relatives. By degrees they will become softened, and he
will probably enjoy the delight of finding them come over to the blessed path he is
himself pursuing. He will also find that self-denial, and a disposition to subject himself to
any trouble or annoyance in order to promote his friends' comfort, or exemption from
some grievance, will have a very powerful effect in conciliating his friends. With all the
courtesy that prevails in high life, no one, I think, can associate with those who move in
it, without seeing how great a share selfishness has in deciding their language and
conduct, saving themselves trouble or money, &c., &c. Happily the objections of worldly
parents to their children becoming religious are considerably weakened since it has
pleased God to diffuse serious religion so much through the higher ranks in society: they
no longer despair, as they once did, of their sons and daughters not forming any eligible
matrimonial alliance or any respectable acquaintances or friendships. The grand blessing
of acting in the way I recommend is the peace of conscience it is likely to produce. There
are, we know, occasions to which our Saviour's words must apply, 'He that loveth father
and mother more than Me is not worthy of Me,' and I doubt not that if your friend does
the violence to his natural feelings which the case supposes, in the spirit of faith and
prayer, he will be rewarded even by a present enjoyment of spiritual comfort. If I mistake
not I wrote to you lately on the topic of the joy which Christians ought to find familiar to
them, still more the peace; and the course he would pursue would, I believe, be very
likely to ensure the possession of them. We have been, and still are, highly gratified by
finding true religion establishing itself more and more widely. Lord Mandeville, whose
parent stock on both sides must be confessed to be as unfavourable as could be well
imagined in this highly favoured country, is truly in earnest. He, you may have forgot,
married Lady Olivia's only daughter. He is a man of very good sense; though having been
destined to the Navy, which had been for generations a family service, his education was
probably not quite such as one would wish. He is a man of the greatest simplicity of
character, only rather too quiet and silent."
"Highwood Hill,
"November 27, 1826.
"I hope you are pleased, I assure you I am, with the result of your B.A. course. And I
scarcely dare allow myself to wish that you may be in the 1st class, or at least to wish it
with any degree of earnestness or still less of anxiety. The Almighty has been so signally
kind to me even in my worldly affairs, and so much more gracious than I deserved in my
domestic concerns, that it would indicate a heart never to be satisfied were I not
disposed in all that concerns my children, to cast all my care on Him: indeed, you pleased
me not a little by stating your persuasion that it might be better for you ultimately not to
have succeeded (to the utmost) on this very occasion. And I rejoice the more in this
impression of yours, because I am sure it does not in your instance arise from the want
of feeling; from that cold-blooded and torpid temperament that often tends to indolence,
and if it sometimes saves its proprietor a disappointment, estranges him from many who
might otherwise attach themselves to him, and shuts him out from many sources of pure
and virtuous pleasure.
"Your dear mother in all weather that is not bad enough to drive the labourers within
doors, is herself sub dio, studying the grounds, giving directions for new walks, new
plantations, flower-beds, &c. And I am thankful for being able to say that the exposure to
cold and dew hitherto has not hurt her—perhaps it has been beneficial."
"August 25, 1827.
"I was lately looking into Wrangham's 'British Biography,' and I was forcibly struck by
observing that by far the larger part of the worthies the work commemorates were
carried off before they reached to the age I have attained to. And yet, as I think, I must
have told you, Dr. Warren, the first medical authority of that day, declared in 1788 that I
could not then last above two or three weeks, not so much from the violence of an illness
from which I had then suffered, as from the utter want of stamina. Yet a gracious
Providence has not only spared my life, but permitted me to see several of my dear
children advancing into life, and you, my dear Samuel, as well as Robert, about to enter
into Holy Orders so early that if it should please God to spare my life for about a couple
of years, which according to my present state of health seems by no means improbable, I
may have the first and great pleasure of witnessing your performance of the sacred
service of the Church. It is little in me—I mean a very ordinary proof of my preference of
spiritual to earthly things, of my desiring to walk rather by faith than by sight—that I
rejoice in the prospect of your becoming a clergyman rather than a lawyer, which
appeared the alternative in your instance; but it is due to you, my dear Samuel, to say
that it is a very striking proof of your having been enabled by, I humbly trust, the highest
of all influences, to form this decision, when from your talents and qualifications it
appeared by no means improbable that in the legal line you might not improbably rise
into the enjoyment of rank and affluence. It is but too true that my feelings would, at
your time of life, have been powerfully active in another direction. Perhaps this very
determination may have been in part produced by that connection to which you look
forward. And may it please God, my dear Samuel, to grant you the desire of your heart in
this particular and to render the union conducive to your spiritual benefit and that of your
partner also, so that it may be looked back upon with gratitude even in a better world, as
that which has tended not only to your mutual happiness during the journey of life, but
has contributed to bring you both after its blessed termination to the enjoyment of the
rest that remaineth for the people of God."
This letter refers to Samuel Wilberforce's marriage with Emily Sargent, as to which his
father remarks: "Viewed in a worldly light, the connection cannot be deemed favourable
to either of you."
"March 20, 1828.
"The cheerfulness, which at an earlier period of my life might have been a copious spring
supplying my letters with a stream of pleasant sentiments and feelings, has been chilled
even to freezing by advancing years, and yet, to do myself justice, though this may have
dulled the activity and liveliness of my epistles, I think it has not cooled the kindly
warmth of heart with which I write to my friends and least of all to my children."
"July 22, 1828.
"I am glad that any opportunity for your coming forward as a public speaker has
occurred, I mean an opportunity proper for you to embrace, in which you were rather a
drawn (though not a pressed) man and not a volunteer. We have had the great pleasure
of having dear Robert officiate twice, both in the reading-desk and the pulpit. The
apparent, as well as real, simplicity of his whole performance must have impressed every
observant and feeling hearer with a very favourable view of his character. His language
remarkably simple, much every way in his sermon to esteem and love. It suggested one
or two important topics for consideration, which I shall be glad to talk over with you
hereafter, as well as with Robert himself. One is, whether he did not fall into what I have
often thought an error in the sermons of sound divines, and in those perhaps of Oxonians
more than Cantabs—that I mean of addressing their congregations as being all real
Christians—children of God, &c.—who needed (to use our Saviour's figure in John xiii.)
only to have their feet washed. Whatever may be the right doctrinal opinion as to
baptismal regeneration, all really orthodox men will grant, I presume, that as people
grow up they may lose that privilege of being children of God which we trust they who
were baptised in their infancy did enjoy, and would have reaped the benefit of it had they
died before, by the gradual development of their mental powers, they became moral
agents capable of responsibility. And if so, should not their particular sins of disposition,
temper, or conduct be used rather to convince them of their being in a sinful state, and
as therefore requiring the converting grace of God, than as merely wanting a little
reformation?"
"November 20, 1828.
"Has Sargent[56] heard of the fresh explosion in the British and Foreign Bible Society? I
truly and deeply regret it. It has proceeded from a proposal to print the Septuagint. In
the discussion that took place on that topic it was perhaps unwarily said there was no
proper standard of the Holy Scriptures. No standard!!!!! Then we have no Bible! You see
how a little Christian candour would have prevented this rupture. Oh that they would all
remember that the end of the commandment is Love. I fear this is not the test by which
in our days Christians are to be ascertained: may we all cultivate in ourselves this blessed
principle and pray for it more earnestly. I am quite pleased myself, Robert is delighted, by
the appointment to the Professorship (Hebrew) of Pusey—above £1,200 per annum.
Pusey had opposition, and is appointed by the Duke of Wellington, solely we suppose on
the ground of superior merit."
"February 20, 1829.
"Legh Richmond,[57] though an excellent man, was not a man of refinement or of taste. I
cannot deny the justice of your remarks as far as I can fairly allow myself to form a
judgment without referring to the book. I entirely concur in your censure of Richmond's
commonplace, I had almost termed it profane, way in which he speaks of the Evil Spirit.
This falls under the condemnation justly pronounced by Paley against levity in religion.
"When I can spare a little eyesight or time, I feel myself warranted to indulge the
pleasure I always have in the exercise of the domestic affections, and in gratifying you
(as I hope it is not vanity to think I do) in writing to you at a time when you are in
circumstances of more quiet than usual, though I am aware that a man of your age, who
is spending his first year of married life with a partner, between whom and himself there
was great mutual attachment, grounded on esteem, and a mutual acquaintance with
each other's characters and dispositions, can never be so happy as when he is enjoying a
tête-à-tête with his bride. By the way, do you keep anything in the nature of a journal? A
commonplace book I take it for granted you keep; and speaking of books, let me strongly
urge you to keep your accounts regularly, and somewhat at least in the mode in which
we keep ours—under different heads. If you have not the plan, tell me and I will send it
to you. Its excellence is that it enables you with ease to see how your money goes; and
remember we live in days in which a single sovereign given by an individual is often
productive of great effects. Where is it that a single drop (stalactite) from a roof, falling
into the ocean, is made to bemoan itself on being lost in the abyss of waters, when
afterwards it became the seminal principle of the great pearl that constituted the glory of
the Great Mogul? And now also, remember the Church Missionary Society is so poor, that
it will be compelled to quit some fields whitening to the harvest, unless it can have its
funds considerably augmented."
SAMUEL WILBERFORCE, Aged 29.
The next letter refers to the offer of the vicarage of Ribchester, near Preston, in
Lancashire, made by the Bishop of Chester to Samuel Wilberforce.
"March 3, 1829.
"Whether regarded in relation to your bodily strength, your spiritual interests, or to
prudence in affairs, I should be disposed to advise you to decline, with a due sense of
kindness, &c., the Bishop's offer. Your constitution is not a strong one, and it is highly
desirable in that view alone that you should for a time officiate in a small sphere, and if it
may be in a place where, as from your vicinity to Oxford, you can have assistance when
you are not equal yourself to the whole duty. With such a scattered population, there
must be a call I conceive for great bodily strength. Secondly, the situation appears to me
still less eligible considered on higher grounds. It is no ground of blame to you that your
studies have not hitherto been of divinity. Supply all that I should say under that head,
were I not writing to one who is capable himself of suggesting it to his own mind. Again,
you cannot have that acquaintance with human nature, either in general, or in your own
self, which it would be desirable for any one to possess who was to be placed in so wide
and populous a field, especially in one so circumstanced as this particular place. Then
you would be at a distance from almost all your friends, which I mention now in
reference to the spiritual disadvantages of the situation, not in relation to your comfort
and Emily's, in which, however, it may be fairly admitted to some weight. Again, I should
much regret your being placed where you would naturally be called to study controversial
anti-Roman Catholic divinity, rather than that which expects the cultivation of personal
holiness in yourself and your parishioners. I could say much on this head. Thirdly, Mr.
Neale sees the objections on the ground of pecuniary interest, as alone of so much
weight, as to warrant your refusing the offer—a vicarage. Its income is commonly derived
from small payments, and in that district probably of poor people whom you would not,
could not squeeze, and yet without squeezing from whom you probably would get
nothing. Most likely a curate would be indispensable."
On the same topic Wilberforce writes again:—
"March 17th, 1829.
"I ought to tell you that in the reasons I assigned to the Bishop for declining his offer,
one, and in itself perhaps the strongest, (nay, certainly so, not perhaps,) was my
persuasion that for any one educated and associated as you have been, it was of very
great importance with a view to your spiritual state, (more especially for the cultivation of
devotional feelings and spirituality of mind,) that he should in the outset of his ministerial
course be for some time in a quiet and retired situation, where he could live in the
enjoyment of domestic comfort, of leisure for religious reading and meditation, and
devotional exercises; while, on the contrary, it was very undesirable in lieu of these to be
placed in circumstances in which he would almost necessarily be almost incessantly
arguing for Protestant principles—in short, would be occupied in the religion of the head
rather than of the heart. I own to you in confidence (though I believe I shall make the
avowal to my dear Robert himself) that I am sometimes uneasy on a ground somewhat
congenial with this, about the tutor of Oriel. For though I doubt not the solidity of his
religious character, yet I fear his situation is far from favourable to the growth in grace,
and would, alas! need every help we can have for the advancement of personal religion
within us, and can scarcely bear without injury any circumstances that have an
unfavourable tendency. I trust my dear Samuel will himself consider that he is now
responsible for living in circumstances peculiarly favourable to the growth of personal
piety, and therefore that he should use his utmost endeavours to derive the benefits that
appear, (humanly speaking,) to be placed within his reach. Oh, my dearest boy, we are all
too sadly lukewarm, sadly too little urging forward with the earnestness that might justly
be expected from those that are contending for an incorruptible crown. Did you ever read
Owen on spiritual-mindedness? There are some passages that to me appear almost
unintelligible (one at least), but it is in the main, I think, a highly useful book. I need not
say how sorry we are to hear of Emily being poorly. But our gourds must have something
to alloy their sweets. D. G. your mother is recovering gradually, and now profits much
from a jumbling pony-chair; its shaking quality renders its value to her double what it
would be otherwise."[58]
"March 19, 1829.
"In speaking of Whately's book I ought to have said that I had not got to the part in
which he speaks of imputed righteousness. I remember it was an objection made to my
'Practical View' by a certain strange head of a college that I was silent on that point. The
honest truth is, I never considered it. I have always been disposed to believe it to be in
some sort true, but not to deem it a matter of importance, if the doctrine of free grace
and justification by faith be held, which are, I believe, of primary importance. Hooker,
unless I forget, is clearly for it; see his sermon on Justification. I trust I need not fear
your misconstruing me, and supposing I can be advising you, either to be roguish, or
shabbily reserved. But really I do think that you may produce an unfavourable and false
impression of your principles and professional character, by talking unguardedly about
Methodistical persons and opinions. Mrs. R. may report you as UNSOUND to the Bishop
of Winchester, and he imbibe a prejudice against you. Besides, my dear Samuel, I am
sure you will not fire when I say that you may see reason on farther reading, and
reflection, and more experience to change or qualify some of the opinions you may now
hold. I own, (I should not be honest if I did not say so,) that I think I have myself
witnessed occasions which have strengthened with me the impression that you may need
this hint.... Have you any parishioners who have been used to hear Methodists or
Dissenters, or have you any who appear to have had, or still to have, much feeling of
religion? I cannot help suspecting that it is a mistaken notion that the lower orders are to
be chiefly instructed in the ordinary practical duties of religion, whereas I own I believe
them to be quite capable of impressions on their affections: on the infinite love of their
God and Redeemer, and of their corresponding obligation to Love and Obedience. We
found peasants more open to attacks on their consciences, on the score of being wanting
in gratitude, than on any other."
"April 3, 1829.
"Articles sent to Mr. Samuel—Bewick, Venn's Sermons (2 vols.), White's 'Selborne' (2 vols.
bound in one), 2nd vol. of 'The Monastery.' A lending library is, I think, likely to be
considerably beneficial. It cannot but have a tendency to generate in the poor a
disposition favourable to domestic habits and pleasures, and to seek their enjoyments at
home rather than in the alehouse, and it strikes me as likely to confirm this taste, to
encourage the poor people's children to read to them. Send me a list of any books you
will like to have for your lending library, and I will by degrees pick them up for you....
"We ought to be always making it our endeavour to be experiencing peace and joy in
believing, and that we do not enjoy more of this sunshine of the breast is, I fear, almost
always our own fault. We ought not to acquiesce quietly in the want of them, whereas
we are too apt to be satisfied if our consciences do not reproach us with anything wrong,
if we can on good grounds entertain the persuasion that we are safe; and we do not
sufficiently consider that we serve a gracious and kind master who is willing that we
should taste that He is gracious. Both in St. John's first general Epistle, and in our Lord's
declaration in John xv., we are assured that our Lord's object and the apostles' in telling
us of our having spiritual supplies and communion, is that our joy may be full. It is a
great comfort to me to reflect that you are in circumstances peculiarly favourable to your
best interests. To be spiritually-minded is both life and peace. How much happier would
your dear mother be if she were living the quiet life you and Emily do, instead of being
cumbered about many things; yet she is in the path of duty, and that is all in all."
"September 7, 1829.
"An admirable expedient has this moment suggested itself to me, which will supersede
the necessity for my giving expression to sentiments and feelings, for which you will give
me full credit, though unexpressed. It is that of following the precedent set by a
candidate for the City of Bristol in conjunction with Mr. Burke. The latter had addressed
his electors in a fuller effusion of eloquence than was used to flow even from his lips,
when his colleague, conscious that he should appear to great disadvantage were he to
attempt a speech, very wisely confined himself to, 'Gentlemen, you have heard Mr.
Burke's excellent speech. I say ditto to the whole of it.' Sure I am that no language of
mine could give you warmer or more sincere assurances of parental affection than you
will have received in the letter of your dear mother, which she has just put into my hands
to be inserted into my letter. To all she has said, therefore, I say ditto. My dear Samuel, I
must tell you the pleasure with which I look back on what I witnessed at Checkendon,[59]
and how it combines with, and augments the joyful gratulations with which I welcome
the 7th of September.[60] I hope I am deeply thankful to the bountiful Giver of all good
for having granted me in you a son to whose future course I can look with so much
humble hope, and even joyful confidence. It is also with no little thankfulness that I
reflect on your domestic prospects, from the excellent qualities of your, let me say our,
dear Emily. I must stop, the rest shall be prayer, prayer for both of you, that your course
in this life may be useful and honourable, and that you may at length, accompanied by a
large assemblage of the sheep of Christ, whom you have been the honoured instrument
of bringing to the fold of Christ, have an abundant entrance into the everlasting kingdom
of God."
"September 28, 1829.
"How much do they lose of comfort, as well as, I believe, in incentives to gratitude and
love, and if it be not their own fault thereby in the means of practical improvement, who
do not accustom themselves to watch the operations of the Divine Hand. I have often
thought that, had it not been for the positive declarations of the Holy Scriptures
concerning the attention of the Almighty Governor of the universe to our minutest
comforts and interests enforced by a comparison with the στοργἡ of parental affection,
we should not dare to be so presumptuous as to believe, that He who rolls the spheres
along, would condescend thus to sympathise with our feelings, and attend to our
minutest interests. Here also Dr. Chalmers' suggestions, derived from the discoveries
made to us through the microscope, come in to confirm the same delightful persuasion. I
am persuaded that many true Christians lose much pleasure they might otherwise enjoy
from not sufficiently watching the various events of their lives, more especially in those
little incidents, as we rather unfitly term them; for, considering them as links in the chain,
they maintain the continuity, as much as those which we are apt to regard as of greater
size and consequence."
"November 21, 1829.
"We have been for a few days at Battersea Rise. But your mother will, I doubt not, have
told you the memorabilia of this visit, and especially the inexhaustible conversational
powers of Sir James Mackintosh. I wish I may be able, some time or other, to enable you
to hear these powers exerted. Poor fellow! he is, however, the victim of his own social
dispositions and excellences. For I cannot but believe, that the superfluous hours
dissipated in these talks, might suffice for the performance of a great work. They are to
him, what, alas! in some degree, my letters were to me during my Parliamentary life, and
even to this day."
"December 17, 1829.
"We ought not to expect this life to flow on smoothly without rubs or mortification.
Indeed, it is a sentiment which I often inculcate on myself that, to use a familiar phrase,
we here have more than our bargain, as Christians, in the days in which we live; for I
apprehend the promise of the life that now is, combined with that which is to come, was
meant to refer rather to mental peace and comfort, than to temporal prosperity. My
thoughts have been of late often led into reflections on the degree in which we are
wanting to ourselves, in relation to the rich and bright prospects set before us as
attainable in the Word of God. More especially I refer to that of the Christian's hope and
peace and joy. Again and again we are assured that joy is ordinarily and generally to be
the portion of the Christian. Yet how prone are but too commonly those, whom we really
believe to be entitled to the name of Christians, disposed to remain contented without
the possession of this delightful state of heart; and to regard it as the privilege of some
rarely gifted, and eminently favoured Christians, rather than as the general character of
all, yet I believe that except for some hypochondriacal affection, or state of spirits arising
from bodily ailments, every Christian ought to be very distrustful of himself, and to call
himself to account, as it were, if he is not able to maintain a settled frame of 'inward
peace,' if not joy. It is to be obtained through the Holy Spirit, and therefore when St. Paul
prays for the Roman Christians that they may be filled with all peace and joy in believing,
and may abound in hope, it is added, through the power of the Holy Ghost."
"Highwood Hill,
"December 31, 1829.
"My dear Children,—For to both of you I address myself. An idea, which for so old a fellow
as myself you will allow somewhat to be deserving the praise of brightness, has just
struck my mind, and I proceed to act upon it. Are you Yorkshireman enough to know the
article (an excellent one it is) entitled a Christmas, or sometimes a goose or a turkey pie?
Its composition is this. Take first the smallest of eatable birds, as a snipe, for instance,
then put it within its next neighbour of the feathered race, I mean in point of size, the
woodcock, insert the two into a teal, the teal into a duck, the duck and Co. into a fowl,
the fowl into a goose, the goose and Co. into a turkey. In imitation of this laudable
precedent, I propose, though with a variation, as our Speaker would say, in the order of
our proceeding, that this large sheet which I have selected for the purpose should
contain the united epistles of all the family circle, from the fullest grown if not largest in
dimensions, myself, to the most diminutive, little William.[61] As the thought is my own, I
will begin the execution of it, and if any vacant space should remain, I will fill it, just as
any orifices left vacant in said pie are supplied by the pouring in of the jelly. But I begin
to be ashamed of this jocoseness when I call to mind on what day I am writing—the day
which, combined with the succeeding one, the 1st of January, I consider, except perhaps
my birthday, as the most important of the whole year. For a long period (as long as I
lived in the neighbourhood of the Lock, or rather not far from it) I used to receive the
Sacrament, which was always administered there on New Year's Day. And the heart must
be hard and cold, which that sacred ordinance in such a relation, would not soften and
warm into religious sensibility and tenderness. I was naturally led into looking backwards
to the past days of my life, and forward to the future; led to consider in what pleasant
places my lines were fallen, how goodly was my heritage, that the bounds of my life
should be fixed in that little spot, in which, of the whole earth, there has been the
greatest measure of temporal comforts, and of spiritual privileges. That it should be also
in the eighteenth century, for where should I have been, a small, weakly man, had I been
born either among our painted or skin-clothed ancestors, or in almost any other before or
after it? As they would have begun by exposing me, there need be no more inquiry as to
the sequel of the piece. Next take my station in life, neither so high as naturally to
intoxicate me, nor so low as to excite to envy or degradation. Take then the other
particulars of my condition, both personal and circumstantial. But I need go no farther,
but leave it to you to supply the rest. And you will likewise, I doubt not, pursue the same
mental process in your own instance also, and find, as may well be the case, that the
retrospect and prospect afford abundant matter for gratitude and humiliation, (I am sure
I find the latter most powerfully called forth in my heart by my own survey). Many thanks
for your last kind letter. You have precisely anticipated what was said by the several
dramatis personæ. It is a real sacrifice for Emily and you to be absent from my family
circle. But the sacrifice is to duty, and that is enough. And you have no small ground for
comfort, from your not having to go through the 'experiment solitary,' as Lord Bacon
terms it, but to have one, to whom you may say that solitude is sweet. But I must
surrender the pen to your dear mother."
The country was at that time extremely disturbed by what were known as the "Swing
Riots."[62] Bands of rioters went about, burning ricks and threshing machines, then newly
introduced, and considered by the labourers as depriving them of the winter threshing
work. Wilberforce seems to have shared this feeling.
"Highwood Hill,
"November 25, 1830.
"Your mother suggests that a threshing machine used to be kept in one of your barns. If
so I really think it should be removed. I should be very sorry to have it stated that a
threshing machine had been burnt on the premises of the Rev. Samuel Wilberforce; they
take away one of the surest sources of occupation for farmers in frost and snow times. In
what a dreadful state the country now is! Gisborne, I find, has stated his opinion, that
the present is the period of pouring out the 7th Vial, when there was to be general
confusion, insubordination, and misery. It really appears in the political world, like what
the abolition of some of the great elements in the physical world would be; the
extinction, for instance, of the principle of gravity."
"December 9, 1830.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like