0% found this document useful (0 votes)
6 views

Java Programming Exercises Volume One Language Fundamentals And Core Concepts Christian Ullenboom instant download

The document is about 'Java Programming Exercises Volume One: Language Fundamentals and Core Concepts' by Christian Ullenboom, which provides around 200 programming tasks with solutions to enhance Java coding skills. It covers various programming paradigms and emphasizes clean code and thoughtful design. The book is intended for individuals looking to improve their Java knowledge and skills through practical exercises.

Uploaded by

toscankrpic
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
0% found this document useful (0 votes)
6 views

Java Programming Exercises Volume One Language Fundamentals And Core Concepts Christian Ullenboom instant download

The document is about 'Java Programming Exercises Volume One: Language Fundamentals and Core Concepts' by Christian Ullenboom, which provides around 200 programming tasks with solutions to enhance Java coding skills. It covers various programming paradigms and emphasizes clean code and thoughtful design. The book is intended for individuals looking to improve their Java knowledge and skills through practical exercises.

Uploaded by

toscankrpic
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/ 89

Java Programming Exercises Volume One Language

Fundamentals And Core Concepts Christian


Ullenboom download

https://ebookbell.com/product/java-programming-exercises-volume-
one-language-fundamentals-and-core-concepts-christian-
ullenboom-58439770

Explore and download more ebooks at ebookbell.com


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

Java Programming Exercises Volume One Language Fundamentals And Core


Concepts 1st Edition Christian Ullenboom

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

Java Programming Exercises Volume One Language Fundamentals And Core


Concepts Ullenboom

https://ebookbell.com/product/java-programming-exercises-volume-one-
language-fundamentals-and-core-concepts-ullenboom-58637136

Java Programming Exercises Volume Two Java Standard Library Christian


Ullenboom

https://ebookbell.com/product/java-programming-exercises-volume-two-
java-standard-library-christian-ullenboom-58439762

Java Programming Exercises Volume Two Java Standard Library

https://ebookbell.com/product/java-programming-exercises-volume-two-
java-standard-library-58637134
Java From Zero Learn Java Programming Fast For Beginners To
Professionals The Complete Guide With Code Examples And Exercises To
Become A Professional Scott Brandt

https://ebookbell.com/product/java-from-zero-learn-java-programming-
fast-for-beginners-to-professionals-the-complete-guide-with-code-
examples-and-exercises-to-become-a-professional-scott-brandt-55838508

Java Programming Mindtap Course List 10th Edition 10th Joyce Farrell

https://ebookbell.com/product/java-programming-mindtap-course-
list-10th-edition-10th-joyce-farrell-50708988

Java Programming For Android Developers For Dummies 2nd Edition Barry
Burd

https://ebookbell.com/product/java-programming-for-android-developers-
for-dummies-2nd-edition-barry-burd-50864416

Java Programming Pandey Hari Mohan

https://ebookbell.com/product/java-programming-pandey-hari-
mohan-21999882

Java Programming 1e Rajkumar K

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

Features:

• About 200 tasks with commented solutions on different levels


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

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

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

First edition published 2025


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

and by CRC Press


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

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

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

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

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

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

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

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


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

DOI: 10.1201/9781003454502

Typeset in Times
by codeMantra

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


Contents

About the Author xv

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

1 Introduction to the Java Ecosystem 6


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

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

v
vi Contents

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

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

3 Classes, Objects, and Packages 78


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

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

Loop Arrays and Output Wind Speed, Wind Direction ⭑ 87


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

5 Character and String Processing 114


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

Determine the Larger Crew Size ⭑ 121


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

Quiz: Lightly Attached 164


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

6 Writing Your Own Classes 176


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

Suggested Solutions 194


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

7 Records, Interfaces, Enumerations, and Sealed Classes 216


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

Quiz: Aviso and Brig ⭑ 225


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

8 Nested Types 238


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

9 Exception Handling 244


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

Quiz: Excluded ⭑ 250


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

10 Lambda Expressions and Functional Programming 263


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

11 Special Types from the Java Class Library 275


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

Compare Superheroes ⭑⭑ 279


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

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

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

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


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

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

xv
Introduction

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

PREVIOUS KNOWLEDGE AND TARGET AUDIENCE


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

• Computer science students.


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

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

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

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

WORKING WITH THIS BOOK


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

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

THE SUGGESTED SOLUTIONS


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

USE OF THIS BOOK


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

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

USED JAVA VERSION IN THE BOOK


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

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

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

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

class VanillaJava { }
 • Introduction 5

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

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

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

> netstat –e
Interface Statistics

Received Sent

Bytes 218927776 9941980


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

HELPING CAPTAIN CIAOCIAO AND BONNY BRAIN


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

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


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

BYTECODE AND JVM


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

Porting Java Programs ⭑


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

public class Application {


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

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

We can now compile the program with

$ javac Application.java

and start it with

$ java Application

Question:

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

TOOLS FOR JAVA DEVELOPERS


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

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

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

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


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

Get to Know Error Messages of the IDE ⭑


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

public class Application {


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

Task:

• Transfer Application.java to the IDE.


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

• Change the file name.


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

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


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

SUGGESTED SOLUTIONS

Porting Java Programs ⭑


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

Get to Know Error Messages of the IDE ⭑


You could deliberately include the following errors:

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

• Be able to do simple screen output.


• Receive user input.
• Be able to distinguish between data types.
• Be able to declare variables.
• Know assignment and operators.
• Be able to use conditional statements.
• Be able to use loops for repetitions.
• Be able to use nested loops.
• Be able to declare and implement subroutines with methods.
• Know the difference between argument and parameter.
• Be able to use overloaded methods.

Data types used in this chapter:

• java.lang.System
• java.lang.Math
• java.lang.ArithmeticException
• java.util.Scanner

SCREEN OUTPUT
In the first chapter, the Java program implemented a simple output. Let’s build on that and learn how to
write special characters (such as quotes), set line breaks, or achieve simple formatted output.

Learn about the SVG Specification


Graphical representations encourage us to engage in playing, which is why we want our Java programs to
draw something. Java SE includes a library that allows you to open a window and draw content, but it's
not done with a few lines of code. Therefore, we want to go a different way, using SVG. The abbreviation
stands for Scalable Vector Graphics, a standard for vector graphics. With SVG, we can easily describe
two‑dimensional graphics in text and write text from our Java programs.

DOI: 10.1201/9781003454502-3 9
10 Java Programming Exercises

Task:

• Learn about SVG with a small example at https://tutego.de/go/trysvgcircle.


• Change the size of the circle on the web page.

Write an SVG Circle on the Console ⭑


There are several approaches for screen output in Java. Usually, the method print(…), println(…), or
printf(…) is used. These methods are located at the System.out object. Besides System.out there
is System.err, but this is reserved for error output. Some developers also use the Console object for
output, we stick with System.out.print*(…).
Captain CiaoCiao needs a filled circle for shooting exercises, which can be printed later. For this
purpose, we want to develop a new Java program.
For screen output, we can use:

System.out.print( "Text without subsequent line break" );


System.out.println( "Text followed by a newline" );
System.out.printf( "Text followed by line break%n" );

Task:

• Create a new class SvgCircle1.


• Create a main(…) method so that we can run the program later.
• Use in main(…) the known print*(…) methods to bring the following text to the console:
<svg height='400' width='1000'><circle cx='100' cy='100' r='50' /></svg>
• Enter the console output to https://tutego.de/go/trysvgcircle, and after clicking Run » you will
see a circle. We want to come back to the web page whenever SVG elements are to be displayed
in the following.
2 • Imperative Programming 11

FIGURE 2.1 Display an SVG output.

• Modify the program so that line breaks occur in the output. The output should be:
<svg height='400' width='1000'>
<circle cx='100' cy='100' r='50' />
</svg>
• Change the program again so that instead of single quotes, there are now double quotes in the
string. The output should be:
<svg height="400" width="1000">
<circle cx="100" cy="100" r="50" />
</svg>

VARIABLES AND DATA TYPES


Variables store information, and variables always have a type in Java. The compiler knows at all times
what kind of variable is declared, and what type of expression is in front of him.
Java has eight built‑in data types: boolean, byte, char, short, int, long, float, and dou‑
ble. You can store numeric values and boolean values into them. The boolean values can be set to true
and false. For numeric values, we have three different groups:

• We have numeric values for Unicode characters and use the char data type for them. In addi‑
tion, we have data types for general integers and floating‑point numbers.
• Integers always have signs. We have four different types of them: byte, short, int, and
long. The types differ according to their number of bytes, which means that the data types
can hold numbers of different sizes.
• For floating‑point numbers, we have float and double available; a double has twice as
many bits as a float to store.

The size of the data types is fixed in the Java specification and does not depend on the particular archi‑
tecture or platform.
12 Java Programming Exercises

Access Variables and Output Their Assignments ⭑


Captain CiaoCiao wants to make shooting targets for novices, advanced, and professionals. The targets
are of different sizes.
Our initial program defined a circle by specifying its center coordinates and radius, but we now aim
to create a modifiable output by incorporating parameters.
Add from the previous task the main(…) method.
Task:

• Declare two int variables x, y and a double variable r in the main(…) method.
• Assign values to the variables.
• Build the assignment of the variables into the output.

Example:

• If, for example, x = 100 and y = 110 and r = 20.5, then the console output should be:
<svg height="100" width="1000">
<circle cx="100" cy="110" r="20.5" />
</svg>
• For manual assignment with x = 10, y = 10 and r = 2.686:
<svg height="100" width="1000">
<circle cx="10" cy="10" r="2.686" />
</svg>
A black circle on a white background is created.

Quiz: Value Ranges ⭑


What is the result of this expression 1000000 * 1000000? Does anything stand out? Why does this
result occur?

Quiz: Does This Add Up? ⭑⭑⭑


If you compute 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 ‑ 1.0, and output the result with
System.out.println(…), is the output surprising?
2 • Imperative Programming 13

Generate Random Circles ⭑


Random numbers play a bigger role in the practice as you might think.
In Java, there is a class Math which provides important mathematical methods. Random numbers
can be determined like this:

double rnd = Math.random();

The method random() is thus an offering of the Math class.


Task:

• Refer to the Javadoc for the range of values in which the result of random() is.
• Extend the circle program so that the radius is random, in the range including 10, but keeping
it smaller than 20. Let the radius still be a floating‑point number.

Example:

• If we run the program twice, the outputs might look like this:
<svg height="100" width="1000">
<circle cx="100" cy="110" r="19.47493300792351" />
</svg>
<svg height="100" width="1000">
<circle cx="100" cy="110" r="10.218243515543868" />
</svg>
Alternative variants for forming random numbers in Java are:

double rnd1 = java.util.concurrent.ThreadLocalRandom.current().nextDouble();


double rnd2 = java.util.concurrent.ThreadLocalRandom.current().nextDouble(/* 0
to */ max);
double rnd3 = java.util.concurrent.ThreadLocalRandom.current().nextDouble(min,
max);
14 Java Programming Exercises

int rnd4 = java.util.concurrent.ThreadLocalRandom.current().nextInt();


int rnd5 = java.util.concurrent.ThreadLocalRandom.current().nextInt(/* 0 to */
max);
int rnd6 = java.util.concurrent.ThreadLocalRandom.current().nextInt(min, max);

Quiz: Dazed and Confused ⭑


Clean Code is a set of best practices that make code easy to read and understand, as well as maintainable,
extensible, and testable. Unfortunately, there are also enough counter‑examples.
What is wrong with the following example?

double höhe = 12.34;


double breite = 23.45;
double tmp = 2 * (höhe + breite);
System.out.println( tmp );
tmp = höhe * breite;
System.out.println( tmp );

Process User Input ⭑


So far, we have done screen output, but have not done any input.
Using new java.util.Scanner(System.in).next*(), we can accept input from the com‑
mand line. Examples:

int number1 = new java.util.Scanner( System.in ).nextInt();


double number2 = new java.util.Scanner( System.in ).nextDouble();
String line = new java.util.Scanner( System.in ).nextLine();

Captain CiaoCiao wants to be able to determine the position of the SVG circle itself.
Task:

• For the circle, take the assignments for cx and cy as integers from the console, and write the
generated SVG fragment back to standard output. The radius remains random.

EXPRESSIONS, OPERANDS, AND OPERATORS


An expression is evaluated and produces a result. Operators can be used to link operands such as literals
or variables.

Quiz: Check In-Between ⭑


To test if a number between is truly greater than min and real less than max, we can write:

boolean isBetween = between > min && between < max;

Is the following syntax also allowed in Java?

boolean isBetween = min < between < max;


2 • Imperative Programming 15

Check If Loot Can Be Shared Fairly ⭑


After a raid on the distillery, Captain CiaoCiao and his crew snatch countless bottles. Now the loot must
be divided, with Captain CiaoCiao getting half (if the number of bottles is odd, he gets less than half, the
captain is that generous). All other robbers should get the same share. But does this add up?
Task:

• Write a program that reads the captured number of bottles from the command line and outputs
how much Captain CiaoCiao obtains.
• Output what is left for the crew.
• Ask for the crew size, and see if the loot can be distributed fairly and equally so that each
crew member gets the same number of bottles. An answer in the form of true or false is
sufficient.

Example:

Number of bottles in total?


123000
Bottles for the captain: 61500
Bottles for all crew members: 61500
Number of crew members?
100
Fair share without remainder? true

Consider how division and remainder value relate.

Do Two Numbers Share the Same Digit? ⭑⭑


Bonny Brain is playing anchor dominoes, which uses tiles with two squares, each containing a value from
0 to 9. She is wondering whether it’s possible to place two tiles end‑to‑end, even if they are rotated, so that
the two squares adjacent to each other have the same values.
Task:

1. Write a program that reads in two numbers, where the numbers are to be in the range from 0 to
99 (both limits inclusive).
2. If the numbers are above 100, only the last two digits are to be evaluated; 100 or 200 would
then be like 00 (i.e., 0), 1111 would be like 11.
3. Test if the two numbers have a common digit.

Examples:

• 12 and 31 have 1 as a common digit.


• 22 and 33 do not have a common digit.

Note: The common digit is not asked, but simply an output true/false. If the number is a single digit,
there is a 0 in front, so 01 and 20 have a common digit, which is 0.

Convert Currency Amount to Coins ⭑⭑


In the currency Liretta, there are Liretta coins with denominations of 2 Liretta, 1 Liretta, 50 Lirettacent, 20
Lirettacent, 10 Lirettacent, 5 Lirettacent, 2 Lirettacent, and 1 Lirettacent. 100 lirettacent is equal to 1 liretta.
16 Java Programming Exercises

Task:

1. Create a new class CoinMachine.


2. The program should first ask for a floating‑point number for an amount of money.
3. Print out how the entered amount can be paid out in Literatta coins. Not all permutations are
requested, but only the smallest number of coins.

Example with input 12.91 (English locale):

Please enter the amount of money:


12.91
6 x 2 Liretta
0 x 1 Liretta
1 x 50 Lirettacent
2 x 20 Lirettacent
0 x 10 Lirettacent
0 x 5 Lirettacent
0 x 2 Lirettacent
1 x 1 Lirettacent

The formatting of the output is not relevant.


The Scanner is localized, so it uses the decimal separator of the respective language when entering
descendant digits.

One Bottle of Rum, Ten Bottles of Rum ⭑


Bonny Brain is a hunter of incorrect language, and she always makes sure that labels are grammatically
correct. Many languages have specific rules for the plural. Every so often it’s “1 bottle” or “99 bottles”, but
also “0 bottles”. Simplifications such as “1 bottle(s)” are typically found in user interfaces.
2 • Imperative Programming 17

Task:

• Create a variable noOfBottles and assign a value to it greater than or equal to 0.


• Program a grammatically correct output depending on whether there are 0, 1, or many bottles.

Example:

• "0 bottles of rum".


• "1 bottle of rum".
• "99 bottles of rum".

The condition operator (?‑:-operator) makes the code compact.

Quiz: The Zero Effect ⭑


Does the following class translate? If so, and you run the program, what is the result?

class Application {
public static void main( String[] args ) {
int zero = 0;
int ten = 10;
double anotherTen = 10;
System.out.println( anotherTen / zero );
System.out.println( ten / zero );
}
}
18 Java Programming Exercises

CONTROL FLOW
Conditional statements such as if‑else statements are crucial imperative concepts. For the upcoming
exercises involving user input validation and processing, we rely on the capability to selectively execute
sections of code based on conditions.

Payday ⭑
Tort Ellini purchased an antique pocket watch from Bonny Brain for 1,000 Liretta and is now responsible
for paying for it.

Task:

1. Write a program that reads in the amount of money on the command line using new java.
util.Scanner(System.in).nextDouble().
2. Bonny Brain is always in a good mood, so she is happy with 10% less. She is also pleased when
Tort offers 20% more. However, if Tort voluntarily pays more than 20%, Bonny Brain has the
impression that something is wrong and the pocket watch probably has a valuable hidden func‑
tion or holds a secret. Consider how to set up the program so that few code changes are needed
when the limits shift on a whim.
3. When Tort has the appropriate amount together, the screen displays "Good boy!"; if the
amount is too low or an attempt is made to bribe, it displays "You son of a bi***!".

Quiz: Wrong Branching ⭑


The following piece of code wants to swap the contents of the variables x and y if x is greater than y. Is
this correct?

int x = 2; y = 1;
if ( x > y )
2 • Imperative Programming 19

int swap = x;
x = y;
y = x;
// x should be 1 and y 2

Convert Liters ⭑⭑
A program should convert liquid quantities into a form that is easy for Captain CiaoCiao to read.
Task:

• From the command line, read in a floating‑point number, the order of magnitude is liters.
• Convert the number according to the following pattern:
• 1.0 and greater: output in liters, such as approx. 4 l for the input 4.
• 0.1 and greater: output in centiliters, about approx. 20 cl when entering 0.2.
• 0.001 and larger: output in milliliters, about approx. 9 ml when entering 0.009.
• The result will always be an integer, and rounding is acceptable.

Example:

• Conversion to mL:
Enter quantity in liters:
0.0124134
approx. 12 ml
• Conversion in cL:
Enter quantity in liters:
0.9876
about 98 cl
• Message if the value is too small:
Enter quantity in liters:
0.00003435
Value too small to display
• Input is already in liters:
Enter quantity in liters:
98848548485.445
approx. 98848548485 l

Create SVG Circles with Random Colors ⭑


In a previous assignment, Captain CiaoCiao called for a black circle on a white background. But there
should be more colors in the mix!
Task:

• Create a new class with a main(…) method.


• Output on the command line randomly, and with equal probability, red, green, and blue.
• In SVG, for circles, you can specify the color with the fill attribute, like this: <circle
cx="20" cy="20" r="5" fill="blue " />. Give the circle a random color.

Example:

• With three program starts, there could be the following screen outputs:
<circle cx="20" cy="20" r="5" fill="green" />
20 Java Programming Exercises

<circle cx="20" cy="20" r="5" fill="blue" />


<circle cx="20" cy="20" r="5" fill="blue" />

Quiz: To Which Block Does the Else Belong? ⭑⭑


Indentations are among the most important principles of clean code. If the indentations are wrong, a
reader may misunderstand the program.
What output does the following program produce?

if ( true ) {
if ( false )
if ( 3!=4 )
;
else
System.out.println( "ship's kobold" );
else
System.out.println( "Pumuckl" );
}

Find the result without translating the program.


Hint: First indent the program correctly.

Quiz: Recognize Negative Days and Hours ⭑


For tests if one of two values is negative, Giggi Giggles always uses expressions like hours < 0 ||
minutes < 0. Now something strange appears in a program:

System.out.println( "Enter number of hours" );


int hours = new java.util.Scanner( System.in ).nextInt();
System.out.println( "Enter number of minutes" );
int minutes = new java.util.Scanner( System.in ).nextInt();
if ( (hours | minutes) < 0 ) // Magic. Do not touch.
System.out.println( "Either the minutes or hours have been negative." );
else
System.out.println( "Minutes in total: " + (60 * hours + minutes) );

Instead of the familiar operator || there is only one slash |. Is this an error? Or why could the result of
hours < 0 || minutes < 0 and (hours | minutes) < 0 be the same?

Evaluate Input Strings for Approval ⭑


Bonny Brain expects approval for new projects, and the approval can vary.
Task:

• Ask for a string from the command line. We assume that the input is always lowercase.
• If the input string is "ay", "aye", "ay, ay", "ja", or "joo", the message "Keep it up!"
should be printed on the screen, all other input strings result in "Don't you dare!".
• Solve this exercise using the switch statement or switch expression.
2 • Imperative Programming 21

Rewrite Switch Statement to Switch Expression ⭑


Java 14 has introduced an extended syntax for the switch statement, allowing for more concise writing
of existing code.
Task:

• Given is the following code with the classic switch statement:


int month = new java.util.Scanner( System.in ).nextInt();
int year = new java.util.Scanner( System.in ).nextInt();
boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0))
|| (year % 400 == 0);
int days;
switch ( month ) {
case 2:
days = isLeapYear ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
}
• Shorten the program with the switch expression.

LOOPS
Besides if statements, repetitions are the second important imperative property. Java provides different
language constructs for loops:

• while loop.
• do‑while loop.
• for loop.
• extended for loop.

Create Rotated SVG Rectangles ⭑


After a raid, Captain CiaoCiao often comes back stressed. To relax, he colors geometric, recurring pat‑
terns. Bonny Brain is supposed to prepare sheets for him, but she dislikes doing it; a program is supposed
to take care of it.
22 Java Programming Exercises

The following vector graphic in SVG rotates a rectangle around the center point (100, 100), by 60
degrees:

<svg height="200" width="200">


<rect x="50" y="50" width="100" height="100" stroke="black" fill="none"
transform="rotate(60 100 100)" />
</svg>

Task:

• Write a program that rotates 36 SVG rectangles 10 degrees on top of each other and outputs
them to the screen.

Example:

• The output starts with:


<svg height="200" width="200">
<rect x="50" y="50" width="100" height="100" stroke="black"
fill="none" transform="rotate(0 100 100)" />
<rect x="50" y="50" width="100" height="100" stroke="black"
fill="none" transform="rotate(10 100 100)" />
<rect x="50" y="50" width="100" height="100" stroke="black"
fill="none" transform="rotate(20 100 100)" />

</svg>

Create SVG‑Pearl‑Chain ⭑
Captain CiaoCiao wants to give a pearl necklace to his beloved Bonny Brain. This is made of three dif‑
ferent gemstones: Sapphire (blue), Emerald (green), Spessartite Garnet (orange). He would like to have a
design proposal in which the colors are randomly arranged.
2 • Imperative Programming 23

The following is for an SVG document with three circles:

<svg height="100" width="1000">


<circle cx="20" cy="20" r="5" fill="blue" />
<circle cx="30" cy="20" r="5" fill="green" />
<circle cx="40" cy="20" r="5" fill="orange" />
</svg>

Task:

• Create an SVG output on the command line with 50 circles side by side.

Sum Numbers from the Command Line ⭑


Captain CiaoCiao needs a program to enter a number of captured Loretta from his individual raids. This
should be entered from the command line to add them up.
24 Java Programming Exercises

Task:

• Create a new class SummingCalculator.


• Use the Scanner to input numbers until 0 is entered. Negative numbers are allowed since
Captain CiaoCiao is occasionally been robbed. Ignore any potential overflows resulting from
numbers that are too large.
• After 0 is entered, the sum should be printed.

Example:

12
3
‑1
0
Sum: 14

Go through a Mathematical Phenomenon ⭑


In mathematics, an iteration is a repeated calculation starting with a starting value until a certain condi‑
tion is met. In calculations, iterations are an important procedure to improve the solution at each addi‑
tional step after an initial approximation.
Task:

• Declare a double variable t between 0 (inclusive) and 10 (exclusive) with the following line:
double t = Math.random() * 10;
• Multiply t by 2 if t < 1. However, if t >= 1, subtract 1.
• Put this calculation into a while loop that should end when t is less than or equal to 0.

Example:

• The output might evolve like this:


9.835060881347246
8.835060881347246
7.835060881347246
6.835060881347246

0.75
1.5
0.5
1.0

Quiz: How Many Stars? ⭑


How many asterisks would appear on the console for loop A and B?
A:

for ( int stars = 0; stars <= 7; stars = stars + 2 )


System.out.println( "***" );
2 • Imperative Programming 25

B:

for ( int stars = 10; stars < 0; stars++ )


System.out.println( "**" );

Remember: stars++ is an abbreviation for stars=stars+1.

Calculate Products for Faculties ⭑


For the new fleet, Rigel VII, Bonny Brain must select the lead officers; the choices are Paul Peldrion, Kate
Muggle, Robinson Langdon, and Lienn Langdon. However, Bonny Brain is unsure which person should
take which role; there are: commander, first officer, second officer, and third officer.
There are many possibilities of which person takes which role. How many possible arrangements of
different elements there are in a row is told by the so‑called permutation. A permutation without repeti‑
tion is calculated by the factorial. With four persons, there are 1 × 2 × 3 × 4 = 24 possible arrangements.
The factorial of a natural number (positive integer) is the product of all positive integers up to that
number. It is defined as follows:

n! = 1 × 2 × 3 × … × (n − 1) × n

It holds that 0! = 1.
Task:

• Write a Java program that reads a nonnegative integer from the command line and displays the
calculation.

Example:

• Input: 9 → Output: 9! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 = 362880.


• Input: 3 → Output: 3! = 1 * 2 * 3 = 6.
• Input: 0 → Output: 0! = 1.
• Input: 1 → Output: 1! = 1.
• Input: ‑1 → Output: Number must not be negative.

Use the data type long internally.


Question: From which number will there be “problems”? How do the issues show up, and how can we
detect them? Can Math.multiplyExact(long x, long y) help us?

Determine If a Number Is Formed by Factorial ⭑


Jar Jar Dumbs has been instructed by Bonny Brain to write down all possible arrangements for a given
number of people. Before looking at the list, she counts the number to determine if all permutations have
been listed.
26 Java Programming Exercises

We saw how to calculate the factorial for a natural number in the previous assignment. But how can
we find out if a number is a factorial? We know that 9! = 362880, but what about 212880 or 28?
Task:

• Write a program that reads a natural number from the command line, and outputs whether the
number is a factorial.

Example:

• Number is factorial:
Enter a number:
362880
362880 = 9!
• Number is not a factorial:
Enter a number:
1000
1000 is not a factorial

Test if the number is divisible by 2, 3, 4, 5 …

Find the Smallest and Largest Digit of a Number ⭑


Bonny Brain knows, of course, that decimal numbers consist of digits from 0 to 9. Since the boat ride is
long and boring, she came up with a game: she gives the crew an integer, and the fastest person to name
its largest and smallest digits wins one Liretta.
2 • Imperative Programming 27

Task:

• Given any whole number (positive or negative), stored in a long.


• Using a program, help find the smallest and largest digits of the stored number.

Examples:

• 12345 → 1, 5
• 987654 → 4, 9
• 11111 → 1, 1
• 0 → 0, 0
• ‑23456788888234567L → 2, 8

Quiz: Not Like This from 1 to 100 ⭑⭑


The compiler does the work for us of checking programs syntactically. Now let’s play compiler!
The following program is supposed to add the numbers from 1 and up to 100 and output the result.
Unfortunately, there are some errors in the program.

class Sümme {
private static int getSum() {
int j == 0;
for ( /* int */ i = 0, i <= 1OO, j++ );
j += i
;
}
public static void Main( String aarg ) {
system.out.println( getsum() );
}
}
28 Java Programming Exercises

Assign the errors to the following types:

1. Syntactic errors.
2. Semantic errors.
3. Style guide violations.

A Flag in the Wind through Nested Loops ⭑


The sailors were in for a surprise when they realized that their flag had gone for a swim in the rough sea!
Captain CiaoCiao, being the witty captain that he is, demanded that his crew whip up a new one ASAP.
Let’s just hope it doesn’t decide to take another dip anytime soon!

Task:

• Create the following output that looks like a small flag:


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Optional: The output should appear as a tree, in the sense that all lines are centered.

Output Simple Chessboard ⭑


Captain CiaoCiao is a fan of German Checkers, which is a variant of the game of checkers. He frequently
takes part in competitions and has noticed that the board size can vary. Sporadically, it is 8 × 8 squares,
and sometimes 10 × 10 squares; he has also experienced 12 × 12 and 14 × 14.
For Captain CiaoCiao to prepare for all possible board sizes, a program should output a chessboard
on the screen.
2 • Imperative Programming 29

Task:

• Obtain from the command line the height and width of the game board.
• Draw the board according to its given dimensions by the symbols # and _ .

Example:

Checkerboard width: 10
Checkerboard height: 5
_#_#_#_#_#
#_#_#_#_#_
_#_#_#_#_#
#_#_#_#_#_
_#_#_#_#_#

It's Christmastime: Displaying Trees with Ornaments ⭑


Christmas is coming soon, and Bonny Brain wants to print Christmas cards. For this, trees of different
sizes are needed.
30 Java Programming Exercises

Task:

• Using loops, write a triangular tree top with a maximum width on the screen.
• In each line, the string becomes wider by two characters until it becomes >= width.
• Centering is achieved by preceding spaces.
• The leaves of the tree consist of the multiplication character *.
• Randomly sprinkle o characters representing Christmas balls into the tree.

Example:

• Tree of width 7 (equal to a tree of width 8):


*
*o*
***o*
*o*****

Draw Fishy Stitching Motifs ⭑


Bonny Brain loves the sea and wants a scarf with a fish pattern. The sewing machine can stitch ><
and > motifs using the symbols ><> and <><.
The following forms a pattern with a repetition of 1, so that first a fish swims to the right and then a
fish swims to the left.

><> <><
2 • Imperative Programming 31

Task:

• Write a program that, according to the assignment of a variable repetitions, first places the
fish ><> repetitions times one after the other and then places the fish <>< repetitions
times one after the other. The line should itself be repetitions times below the other.

Examples:

• If repetitions is equal to 2, the output shall be:


><> ><> <>< <><
><> ><> <>< <><
• If repetitions = 3 the program shall result in the following output:
><> ><> ><> <>< <>< <><
><> ><> ><> <>< <>< <><
><> ><> ><> <>< <>< <><

Trying Instead of Thinking ⭑⭑


Today’s computers are so fast to try different things at the same time. Password cracking programs work
on this principle.
32 Java Programming Exercises

Captain CiaoCiao flips through the “Pirates Daily” and finds a brainteaser:

X O L
+ L X X
= T L T

He has to find a digit for each of the letters L, O, T, and X to make the calculation correct. The prize
for the puzzle is an old compass, which Captain CiaoCiao desperately wants to win. But unfortunately, he
lacks the desire to think.

Task:

• Develop a program that finds a solution by trying all possibilities.


• Print out all the solutions and indicate which solutions have X, O, L, and T all different from
each other.

Get the Number of Digits of a Number ⭑⭑


Bonny Brain wants to right‑justify numbers. To accomplish this, spaces are placed in front of the numbers.
For example, if you want the width to be 10 characters and the number is 123 (three digits), then seven
spaces must be placed before the number to make the width 10.
The first step to determine the number of spaces is to determine the number of digits in a number.
Task:

• Given is a positive integer n of type int. Output the number of digits of the number. Do not
use (""+n).length(), that would be too simple …
2 • Imperative Programming 33

Examples for n and the expected output:

• 1234 → 4
• 3→1
• 0→1
• Integer.MAX _ VALUE → 10

METHODS
Methods are important because this way we can centralize common code and also give objects an API to
access for clients.

Drawing Hearts ⭑
Since Captain CiaoCiao loves his crew, there can’t be enough hearts.

Task:

1. Create a new class LinePrinter. Put a static method line() into the class, which writes a
line of ten hearts. Java can store and output the Unicode character “♥” in strings.
2. Create a new class LinePrinterDemo that has a main(..) method and calls line().
34 Java Programming Exercises

Implement Overloaded Line Methods ⭑


Next, let’s look at methods that can be passed something. Furthermore, a method name can be used mul‑
tiple times: we talk about overloaded methods.
Task:

• A method line(int len) will print a line of length len with a minus sign ("‑") on the
console. For example, line(3) will print ‑‑‑ onto the screen.
• The method line(int len, char c) shall be callable with custom fill characters. So
line(2, 'x') outputs the line xx on the screen. Can the first method use the second?
• Add another overloaded method line(String prefix, int len, char c, String
suffix) that sets a start string before the line and an end string after the line. For example,
line("╠", 3, '═', "╣") returns ╠══╣. The line inside is three characters long, not the
entire string.

Remember: you don’t have to implement all three methods completely with a loop. If you’re smart, you’ll
forward from one method to the other.
Add the overloaded methods to the class LinePrinter.

Standing Straight ⭑
Back in the day, the nincompoops would hoist the mast at the wrong angle. A pirate can be a bit crooked,
but the mast better be straight as an arrow!

If you take a triangle, it can come in a variety of shapes. There are acute‑angled triangles, obtuse‑angled
triangles, equilateral triangles, and right‑angled triangles, among others. As a reminder, triangles are
right‑angled if c2 = a2 + b2.
Random documents with unrelated
content Scribd suggests to you:
significance. I suppose most of us feel this in comparing, for example,
Tennyson with Browning; and, consciously or unconsciously, have had a
feeling of it in the presence of many pictures, even by acknowledged
masters. Not improbably it is the latent reason of so much indifference
toward pictures in this country by persons otherwise cultivated. Our past
history, as well as the immediate present, has demanded qualities essentially
masculine, and so many people instinctively suspect the superabundance of
the feminine in painting, or have regarded it merely as a pastime on the part
of the painter, and as suitable chiefly for decorating the walls of a drawing-
room. The one class has ignored the claims of painting; the other committed
itself unreservedly to that kind of picture, which is least of all the product of
intellect, or likely to make any demand upon the intelligence. They have
found it difficult to take a painter and his work seriously, or would be,
perhaps, surprised to find that such an attitude toward art could ever be
expected of them. They would find incomprehensible the suggestion that a
man may be found who puts into a picture as much mind and force of mind
as another man puts into the upbuilding of a great business; that the
qualities of mind expended in each case may be similar in degree, and not
altogether different in kind; power to forecast the issue, and to labour
strenuously for it, with a capacity for organization, for selecting, rejecting,
and coördinating; a gift of distinguishing between essentials and non-
essentials, and of converting sources of weakness into strength, so that the
issue becomes in each case a monument to the intellect of its creator. And
when one finds, as with Martin, that these big qualities of mind have been
directed to the expression of what is grand in nature, least transitory, most
fundamental, one begins to have that respect for his art which must precede
all true appreciation, and to discover that it has a close relation to what is
noble and most endearing in life—a deep, abiding reality. During his
lifetime comparatively few appreciated the significance of his work, but it
is of the kind that time is justifying.
A very characteristic example is the “Westchester Hills,” because it is at
once so powerful and so free from any of the small and perfectly legitimate
devices to attract attention; a picture that in its sobriety of mellow browns
and whites (for such, very broadly speaking, is its colour scheme) makes no
bid for popularity; in a gallery might escape the notice of a careless visitor,
and grows upon one’s comprehension only gradually. In the gathering
gloom of twilight we are confronted with a country road crossed by a thread
of water and bounded on the right by a rough stone wall. The road winds
away from us, skirting the ridge of hill, which slumbers like some vast
recumbent beast against the expanse of fading sky. The dim foreground and
shadowed mass

From the collection of Daniel Guggenheim, Esq.

WESTCHESTER HILLS.
By Homer D. Martin.

From the collection of Louis Marshall, Esq.

THE SUN WORSHIPPERS.


By Homer D. Martin.
are grandly modelled; strength, solidity, and bulk, contrasted with the
tremulous throbbing of the light. This contrast of rude, tawny ground with
the vibration of a white sky recalls a favourite theme of the French painter
Pointelin; but one feels that a comparison of his pictures with the
“Westchester Hills” is all in favour of the latter. Both painters have felt the
solemn loneliness of nature folding her strength in sleep, the mystery of
darkening and of the lingering spirituality above; but Martin is the grander
draughtsman of the two, suggesting with far more convincingness the solid
structure of the earth. So we are made to realize that the phenomenon is not
merely one that he has noted or that we might note, but one that through
countless ages has manifested itself as part of the order of the universe.
Its significance is elemental. We may attribute this to the better drawing,
or, with far more justice, to the superiority of intellect, that could embrace
this larger conception and find the means to express it. And in studying the
means let us not overlook the essential grandeur of the colour; not of the
brave or passionate kind, but sober with a concentration of subtle meaning,
that discovers infinite expression in the minutest variations of the homely
browns and yellows, which in the shadow yield nothing but their strength
and quietude. And, then, what a wonder of suggestion in the sky! It is not
only lighted, but quivering with light; an elastic fluid that extends as far as
one’s imagination can travel, in height, and breadth, and depth. These
limitless skies are a characteristic of Martin’s pictures. He does not seem to
have been attracted so much by cloud forms or to have been given, as it
were, to building castles in the air; but his imagination loves to free itself in
the far stretches of ether, the circumambient medium through which the
waves of light travel. His skies are brushed in with firm assurance; it is a
pleasure to peer into the canvas and study the sweep and exultation of the
strokes, and then to step back until distance blends them into a unity of
ranging grandeur. And just as Corot said of himself, that he was “like a lark
pulsing forth its songs amid the gray clouds,” and his skies have the
vibrative quality of violin music, so there is music in these skies of
Martin’s, only it is that of the organ and the diapason stop. True, the note is
not always so full and sonorous; as, for example, in the “View on the Seine”
in the Metropolitan Museum, where the splendid blue and white have a
more silvery resonance, which, however, is less suggestive of songfulness
than of the sweep of music travelling on and on. Indeed, in all his skies,
there is less of local significance than of the suggestion that the ether is a
tidal ocean connecting the fragment of circumstance with infinity.
This landscape also shows that his imagination was not wedded to the
solemn. It is brisk with the joie de vivre, and yet not in a merely sprightly
way. In the line of poplars on the right of the picture, each spiring up into
the sky, there is the sense of springing aspiration. Again, in that beautiful
“Adirondack Scenery,” with its waves of brilliant foliage rolling between
the brow, on which we feel ourselves standing, and the distant cliffs of
mountains, what exuberance of spiritual joy! Spiritual, indeed, for the
picture was painted far away in the West, indoors, and under the affliction
of failing health. But who would guess it from the picture? Martin had so
possessed himself of the sweetness and majesty of the Adirondacks, that he
could give out from himself, drawing upon the treasures of his memory. It
was his swan song, and how characteristic of the essential nobility of the
man, that it breathes such ample serenity, such a boundless sense of beauty,
pure, spacious, and enduring! He never dwelt upon his troubles, as smaller
men do; and this last picture is a grand assertion of the supremacy of mind
over matter,—a poet’s triumphant proof that his dream of beauty was strong
within him to the last.
Martin’s work, like that of other great men, was uneven in quality. But if
it lacks at times perfect intelligibility of construction or of form, it was not
from want of knowledge or ability to draw, as is abundantly proved by the
superlative excellence of these very qualities in his finest pictures. He had
made countless studies, drawn with the greatest care, revealing a thorough
feeling for and comprehension of form. At times, he may have found a
difficulty in translating his knowledge into paint. His use of the brush, used
as he needed to use it to express what he had in mind, had been necessarily
self-acquired, and often it was rather the subtlety of the effect he desired to
express than any fractiousness of the brush, which caused him to fumble,
though, in the majority of his work, never sufficiently to distress us or to
divert attention from the message that his picture conveys. For always, in
his best pictures, there is this distinction of a message; not a mere friendly
interchange of views between the painter and his friend, or simple, easy
platitude regarding nature’s beauty, but a deep, strong, personal assertion of
some specific truth of beauty, fundamentally and enduringly true. It is the
sort of message that appeals to the depth and
From the collection of Samuel Untermeyer, Esq.

OLD CHURCH IN NORMANDY.


By Homer D. Martin.
earnestness in ourselves; and with a comprehensiveness that permits each of
us to draw from it what particularly satisfies himself,—qualities that are the
unfailing distinction of the great works of imagination.
Some of his pictures, in which we shall find these qualities conspicuous,
are “Normandy Church” and “Normandy Farm,” painted during the years
that he lived at Villerville and Honfleur, “The Sun Worshippers,” “Autumn
on the Susquehanna,” “Sand Dunes, Lake Ontario,” and “Headwaters of the
Hudson.” Individual preferences count for very little; but I cannot resist the
pleasure of recording a particular fondness for the “Normandy Church” and
“Sand Dunes.” In the former it will be remembered how the roof and tower
of the church, embrowned with centuries softened by moss and lichen,
stand like an embodiment of stability against the quiet movement of fleecy
clouds that cross the blue sky, like a token of faith and protection to the
little cottage on the left. It is an idyl of the permanence of hope and
consolation in a simple faith. Then what a full-lunged inspiration of rest and
vastness does one draw from the “Sand Dunes”! It is not the vastness of
distance, for the evening sky is wrapping with greenish gray the sand
hillocks, which are separated from us only by a belt of warm green-brown
grass and a strip of golden-brown scrub. But it is the character of the scene
that is vast in suggestion. We do not feel the sky to be a quilt of softness,
but an abyss of tenderness, assuaging the desolation of the spot,—a
desolation that has the feeling of primeval loneliness.
For, at the risk of repetition, I would dwell once more upon the elemental
quality that characterizes all the best work of Homer Martin. Not only is his
theme elevated and serious, clothed moreover in pictorial language of
corresponding significance, but it shuns the trivial and transitory and
attaches itself to what is basic in nature’s beauty and perennially true. In his
masterpieces there is the evidence of a great mind, for the time being
unreservedly consecrated to great ends, and expressing itself in an imagery
of grandeur and enduring suggestiveness. To recognize these qualities is to
rank him highest of all the poet-painters of American landscape.
IX

GEORGE DE FOREST BRUSH

T O many a young student, regretfully turning his back on the few bright
years of study in Paris, has come the question, “What must I do to be
saved?” Hoping all things, believing all things of his single
determination to succeed, he feels within him a capacity; but how shall he
apply it? I fancy there are two classes of such aspirants: those who look
around them for suggestion, and those who look within. Among the latter
seems to have belonged George de Forest Brush.
Knowing him in the light of his later work, we may feel it one of the
anomalies of art that his master in Paris should have been Gérôme. Yet
looking back over our own lives, we realize that it was the element of
character, the presence or lack of it in those with whom we came in close
contact, that determined their influence upon us. And this quality of
character was strong in Gérôme,—of all the more value to Brush because it
was of a kind in many respects so dissimilar to his own. He is something of
a rebel,—I use the word in its most respectable sense—intellectually
independent, prone to dissatisfaction with things as they are,
unconventional, perhaps a little impractical and visionary, as rebels are apt
to be,—qualities, all of them, that are facets of character. Gérôme, however,
a conservative, addicted to rote and rule, with his scholarly devotion to
semi-classicalism or, as some more severely style it, pseudo-classicalism; a
cold precisionist, who would render the death of a Cæsar as accurately and
dispassionately as a surgeon dissects a corpus—such a character would be a
wholesome make-weight to a young romantic mind.
It would emphasize especially the need of knowledge and mastery of
facts, encouraging the formation of a stable basis on which romance, if it
were minded to push its head into the clouds, might at least have sure
foundation for its feet. Certainly, one accomplishment that Brush brought
back from Paris was a feeling for form, and another was a faculty of seizing
upon the reality of things and of keeping close to facts. No doubt it is as a
painter of ideas that he is significant; but do not let us overlook the point
that all his work, especially the earlier examples, shows an appreciation of
the actual. How much of this he owes to the influence of Gérôme it would
be hard to estimate; but even if this realization of the mental and artistic
value of the actual is an element in his own character, the contact with this
master must have done much to give it fibre. For the sense of actuality is
communicable, while ideas are not only personal to their author, but
inalienable. And how distressingly elusive, tame, and profitless in pictures
are ideas unbased on actuality—the landscape, for example, that makes for
sentiment without support of drawing and construction. In pictures of the
human figure an inspired control of colour may fill us with enthusiasm, but
cannot wholly stifle our regret if the drawing is inadequate; for the beauty
of nature is the beauty of its forms and of the coloured raiment that clothes
the forms without disguising them, while in the world of spiritual ideas the
beauty depends upon their association with or analogy to the world of
matter.
So let us recognize the value of the master’s influence upon Brush.
There was much that he had to unlearn as he pursued his own evolution,
notably the sleek, hard, and dispassionate method of Gérôme’s painting. But
his brush work every painter of distinguished character must acquire
gradually for himself, just as a writer, if he is an honest craftsman, will
discover his own fashion of words, adjusting his method of expression to
what he is trying to express; the main thing, both for painter and writer,
being to have something to say: something which is a part of the man’s self
and convictions. The method will grow to it.
Leaving Gérôme’s studio, Brush, like other students, stood at the
dividing ways. He might have cast his eye around him, noted what seemed
to be the tendencies of the day in art, the “latest style,” as the fashion-
makers call it, and set to work to reproduce in New York the impressions
aroused in Paris. Then, in time, he would have been among those who
excuse their own lack of initiative with the lament that in our city there is
no “art atmosphere.”
In the sense they seem to mean it, the absence is not an unmitigated evil,
for what is this “art atmosphere,” when you search it closely? A little,
perhaps, like Scotland, as characterized by a Scotchman, “The most
beautiful country in the world to live out of.” So it is well to know there are
places where the art atmosphere abounds, that one may visit for a time with
pleasure and profit; yet it is remarkable how the great painters, the men of
force and character, whose minds push them on continually, live either
outside of it or within it behind closed doors. The smallness inseparable
from an art atmosphere, the mutual admiration and amiable reciprocity of
patting of backs, or worse, the “Bully, my boy!” to his face, and the “How
he’s missed it!” behind his back; the petty rivalries of little cliques that
clutter of themselves across a café table, setting up little standards and
gaining brief conspicuousness by repeating one another’s efforts—this is
not the sort of atmosphere that strong painters need to breathe. They would
be stifled in it. They need, like Delacroix or Puvis de Chavannes, the ample
privacy of their own inner life, or, like the Barbizon men, the large
seclusion of nature. For such an atmosphere a painter of Brush’s calibre
would have no use.
He returned to this country; not to city life, but to the wide freedom of
the western territories, and found inspiration for his imagination among the
Indians. I know nothing of what impelled him; whether it were a survival of
a boy’s enthusiasm for the story of his country, or a suggestion received
from the archæological associations of Gérôme’s studio, or some happy
chance of idea, seized upon and followed out; but the significant point is
that, though fresh from Paris, or, shall we say? because of it, he found
motives that attracted him in America. The older men had found them too,
but many of the younger generation, returning from Europe, were
proclaiming, and many do so still, that the conditions of America are
unfavourable to pictorial motives. May it not be that the barrenness is in
themselves? I am not speaking of the landscape painters, but the figure
men. One of their laments is the lack of picturesque costumes. This same
word “picturesqueness” has been the bane of painting for two hundred
years, implying the necessity of certain formulated qualities in a landscape
or figure, rendering it suitable for the purposes of a picture. Owing to this
obsession, Corot was fifty years old and had paid three visits to Italy before
he, poet though he was, could feel the suggestion of loveliness in the
scenery of his native country. So one must not be too hard on others who
are deaf to the calling of their environment. But let us give no quarter to
picturesqueness. It is a discredited, discreditable evasion of the facts. The
true painter sees pictures all around him or evokes them from his
imagination; the world of matter or of spirit continually presents itself to
him in pictorial fashion; it is only a journeyman who hunts for picturesque
jobs.
It may be said that possibly it was just this picturesque quality in the
Indians that attracted Brush. I cannot say; but had he penetrated no further
than the unusualness of their costumes and habits, as is the case with others,
so far as I know, who have painted them, there were nothing to be said. But
he has penetrated into the life and thought of the Indian, and, more than
that, has re-created in his pictures something of the primeval world; its vast
isolation, silence, mystery. He has found in these modern redmen a clue to
their past and has created a series of picture-poems which have the lyric
melody of Longfellow’s “Hiawatha,” an equal individuality and appeal to
the imagination and a greater virility. Let me instance “Silence Broken”—a
little glimpse of river, banked with dense foliage, out of which a goose has
burst above an Indian in his canoe. It is a small picture, representing a
contracted spot, but it needs very little imagination to make one feel that
this fragment of seclusion is part of an immensity of solitariness. The man,
kneeling as he plies the paddle, looks up in no wise startled, but with a
grand composure that seems a part of the elemental suggestion of the scene.
It is a work of powerful imagination, projecting itself upon the solemn
spaciousness and mystery of the past.
Recall, too, another small canvas of big significance, “Mourning her
Brave.” Standing by her dead in the snow, high up on a mountain ledge, the
woman utters her dirge to a leaden sky. What emptiness and desolation of
world without and spirit within! A breath of the ceaseless mystery of sorrow
throbbing out of the void of time! Then a tenderer feeling pervades “The
Sculptor and the King.” Stroke by stroke the sculptor has compelled the
marble to respond to his thought, or wooed it, for he has a gentle, dreamy
face; a youth only dimly conscious of his desires, and he waits for the
king’s verdict, tremulously eager, and withal so glad in his heart at what his
hands have found the skill to do; a poetic embodiment not only of the
primitive man’s yearning after expression, but of the springtime of every
artist’s soul. Then note the king, standing with folded arms, wrapping his
doubt of the desirability of such things and, yet, his wonder and admiration
of them in the convenient impenetrability of silence. There is a touch of
humour in this figure, as of the critic non-plussed and unwilling to commit
himself, but much more of serious reference to the early dawnings of a
comprehension of the beautiful, as “a thing to be desired to make one wise.”
Those Indian subjects are of a high order of imaginative work. They
have a great power of suggestion, stirring directly and forcibly one’s own
imagination; and they are informed with an elevation of thought, a deeply
penetrating earnestness

From the collection of Miss Henrietta E. Failing.

THE SCULPTOR AND THE KING.


By George de Forest Brush.
From the Museum of Fine Arts, Boston. Copyright, 1897, by Foster Brothers.

MOTHER AND CHILD.


By George de Forest Brush.
and a largeness of conception that has been able to grasp the big
significances and to feel them in their relation to perennial truth. For they
not only suggest the life and environment of the early redman, picturing
both with a fulness of comprehension that brings them vividly to our
consciousness, but they involve allusions to our own experience. There are
periods of sorrow when the world seems very empty and desolate to-day;
there still are yearnings after higher things, the flutterings of doubt and hope
that precede the beginning of growth of something better; and still a
grandeur in the solitude of nature and maybe in that of a man’s own
communings with himself. We may or may not have experienced those
things, but, at least, we have an intuition of their possibility; and if a picture
can recall the past and show it as part of the eternal relation of spirit and
matter, we are justified in honouring its author. So these pictures of Brush’s
seem to me great, notwithstanding a certain smallness—I will not call it
pettiness—in their execution. As I recall the “Mourning her Brave,” it has
considerable breadth of method, and, no doubt, others of the Indian series
show increase of manual accomplishment. But the painting in “Silence
Broken,” still influenced by Gérôme’s, is hard and shiny; and the drawing
in “The Sculptor and the King” has a quality of timorous and laboured
exactness. It is not in consequence of style, but despite it, that they are
impressive.
With the artist’s personal development has come maturity of
craftsmanship. His latest series of “Mother and Child” are marked by
fluency of composition both in the lines and masses and in the colour
schemes. But with the ripening of his powers has scarcely followed increase
of individuality. He has freed himself from the hard, evenly lighted, rather
tight character of Gérôme’s manner only to yield himself to the fascination
of the old Italian style. It is a little surprising that one whose imagination is
so individual should have failed to discover a really personal language of
expression. It would seem as if the lack of facility was beyond his power to
remedy, and that, feeling the need of broadening his method, and conscious
that breadth with him would mean chiefly a larger kind of precision, he had
found in the example of some of the Italian masters just that union of
qualities. Then, too, if he were searching for precedents it is to the dignity
and quietude of the Florentines that such a temperament as his would turn.
And in these later pictures one is conscious of these qualities. They have an
air of noble sweetness, serenity, and high and earnest purpose, creating,
wherever they appear, an atmosphere of their own, pure and elevating as
that of the upper air. Yet, as creative work, I think many will rank them
lower than the promise of his early days. Their motive is a borrowed one—
borrowed with their technique. True, it is one of beautiful human
significance, but its representation, especially to one who is a husband and a
father, makes a comparatively small demand upon the imaginative faculties.
So that, if we feel the evidence of these faculties in painting to be the rare
and superlative thing, the artist’s persistence upon a somewhat lower plane
of endeavour must seem regretful. It is rather a merging of the artistic
prepossession in the human.
And I wonder whether this may not be the explanation. In early
manhood, while the impulse was from within, he sought the objective for it
in the world outside, characteristically choosing those scenes which would
least interfere with the seclusion of his own mind. In later years he has
found the seclusion in his own home, yielding to the natural tendency, as
the years grow upon one, to feel the world to be less and less, and those
closest to one more and more. And, it must be remembered, the conditions
of the world were never quite to his liking, while his home is what he has
made it and would have it. Yet this, after all, represents the evolution of a
man rather than of the artist—a yielding to circumstances, inclinations,
conveniences, rather than a following of one’s star.
I write these words with hesitation, as it may be my own fault that I do
not detect in these later works as much evidence of elevated imagination as
in the Indian studies. If so, I would plead in extenuation my enthusiasm for
those earlier pictures.
X

ALEXANDER H. WYANT

T HERE is a species of ivy in England—I do not know if it exists in this


country—that grows over old stone walls and towers. It is treelike in
character and size. Probably it was never planted deliberately against
the masonry, but reached its habitat by one of those romances of nature’s
accidents. Finding the support that its young life needed, it clung and
mounted; gradually, however, gaining independent strength until in the
maturity of its growth it has its own boughs, so hardy that a man may climb
by them, and puts forth bunchy masses of leaves and berries that disguise
the original support in a luxuriance of independent growth.
Such is often the story of an artist’s development, and is that of Wyant’s.
In the small town of Defiance, in Ohio, where he lived, there was little to
suggest to the boy what pictures meant, and yet he had the picture-making
faculty in himself: the observant eye and desire to translate into line the
forms of things. He drew incessantly: the forms of stones, of banks, and tree
roots, their stems and branches, and made studies of the leaves, separately
and minutely, as well as in masses. I like to think of him as a child lying full
length before the kitchen fire with a bit of burnt wood taken from it,
drawing on the floor; and fancy that in that soft, suggestive medium of
charcoal, and on the rough surface of his improvised panel, he may have got
his first dim consciousness of the meaning of synthesis in landscape; the
securing of character and tone, and the fascination of working in masses
rather than in outline.
When he was old enough to be set to a trade, he was apprenticed to a
harness maker, working in his leisure hours at sign painting. But all roads
lead to Rome, and a youth might derive much skill in form, as well as
breadth of manner, in this humble department of the fine arts. Somewhere
about the fifties he found himself in Cincinnati, even then an oasis in the
desert of western indifference to, or ignorance of, art. It was here, in a
private collection, that he first discovered what painted pictures were like,
and, with a rare instinct for one so young, it was Inness’s work that captured
his imagination. A youth, passionate and eager as Wyant was, must have his
god or goddess; a being infinitely above him, yet, perhaps, of infinite
condescension, who will listen to his devotion. Some of us may have
offered our heart and future to ladies nearly old enough to be our mothers;
Wyant’s divinity was of the other sex, an Apollo at whose oracle he would
inquire. He found the means to come to New York and lay his sketches
before the master, and never forgot the kindly criticism which bid him be of
good courage and persevere.
He was now about twenty years old, and nearly ten more years were to
elapse before his own independent growth was to establish itself.
Meanwhile its direction had been assured by the influence of Inness; its
manner of growth was to be partly affected by the Norwegian painter, Hans
Gude, who had graduated from Düsseldorf and was at this time working in
Carlsruhe. He had been the pupil of Achenbach, who, as Muther says, had
“taught him to approach the phenomena of nature boldly and realistically,
and not to be afraid of a rich and soft scale of colour.” He had felt the
influence, also, of Schirmer, whose fondness for the so-called Italian
landscape had guided him to the “acquisition of a certain large harmony and
sense for style in the structure of his pictures.” Such was Gude, to whom
Wyant went for instruction. He spoke in after years of the kindness with
which he had been received as almost one of the household by the painter
and his good frau, and one may imagine that the student took much profit
from the master’s emphasizing of form and construction, and also from the
reposeful dignity, academic though it was, of his compositions. But when
the older man passed from the teaching of principles to that of methods, and
urged his pupil to imitate his particular manner of presenting the truths,
Wyant’s independence rebelled. He had learned what could properly be
taught, and recognizing that for the rest he must depend upon himself,
returned to New York.
Face to face with the problem of making a living, and hoping to gain
useful experience, he joined a government exploring expedition to the West.
But the party suffered terrible hardships, to which Wyant’s physique
succumbed. He was put upon the train to return East, and might have
stopped at his mother’s home to be nursed and cared for. And much he
needed tending, for he was helpless, stricken with paralysis; but the mind in
his poor body was still active; he argued that to be taken off at a far western
station was to become stranded, to lose all touch with the painter’s life, on
which his determination was still fixed. So he let himself be carried past his
home and reached New York. No words can add to the pathetic heroism of
this decision. But in our admiration of the delicate poetry which belongs

From the collection of George A. Hearn, Esq.

THE MOHAWK VALLEY.


By Alexander H. Wyant.
From the collection of Samuel Untermeyer, Esq.

THE CONNECTICUT VALLEY.


By Alexander H. Wyant.
to the work of Wyant that we know best, let us not lose sight of the force of
will-power that was involved in the making of it. “Yes, he had been in
hell!” exclaims Carlyle of Dante; and while suffering may not be the only
road to highest effort, it is one of them, and the man who passes along it
like a man, even if he cannot tread it, but must be carried, as in Wyant’s
case, is very apt to produce something more than ordinarily appealing to the
hearts of other men. While Wyant recovered the use of his body, though
obliged ever after to paint with his left hand, he was never really free from
some bodily discomfort; and I wonder whether this may not have had some
influence upon his notable preference for depicting nature at the hush and
restfulness of twilight. To one whose days were, more or less, days of
weariness, constantly sensible of the afflictions of the body, with what a
benediction the evening would come, full of spiritual refreshment! Out of
the cool cisterns of the night his spirit would drink repose.
For many years he made his summer home in the Adirondacks; then,
fearing that he was getting too much into a groove in his way of seeing
nature, he transferred his study to the Catskills. The move is characteristic
of his alert sensitiveness to nature’s impressions. His temperament was like
an Æolian harp, delicately attuned to nature’s breath, responsive to its
faintest sigh; but he dreaded lest the melody might become too uniform, too
much a merely passive expression. There was a similar mingling of purpose
and of surrender in his relations with his fellows. To a few friends, among
them always Inness, he gave a welcome, and no little of his time and means
in constant acts of kindness to those who needed help; but from social or
official functions he kept, as far as possible, clear. He had so much that in
his heart he longed to do, had begun his life’s work comparatively so late,
and knew the years left to do it in were few. It was only by unremitting
application that he could realize his ideal.
This concentration of endeavour affected his ideal, limiting the range of
moods of nature that he strove to represent. Such versatility as Inness’s and
that painter’s alacrity of impression to constantly differing phases of nature
were impossible to his temperament and circumstances. Drawn by both to
isolate himself, he heard in the silence of his own heart the still small voice
of nature, listened for it always, and strove to woo it. The echo of it is felt, I
think, in all his landscapes. We may recall some of his large woodland
pictures, in which sturdy trees are gripping the rocks with their roots.
Strength and stability and the evidences of time confront us, just as they
would in the forest itself; but like cathedral architecture when music is
pulsing through it, they are for the moment secondary to the spiritual
impression of the voice. Wyant heard it in the movement of the tree-tops,
and in the stir of weeds and ferns that nestled in the hollows, and it
whispered to him of peace, a quiescence that stirs the soul to gentle activity,
gladsome by turns or subdued in the alternate sun and shadow, that
inexhaustible mystery of nature’s peace that passeth man’s understanding.
We have all felt it and know how far it is from our everyday lives, and we
look to word-poets and to poet-painters to create an illusion of it. Surely no
American painter has done this more irresistibly than Wyant. Nor is there
wanting to the peace of his pictures at times a more solemn suggestion.
While so many of his twilights breathe simply the ineffable loveliness of
quiet, others are astir with persuasion to spiritual reflection, with the gentle
admonition to sadness that itself is purifying, or with deeper, fuller
suggestion of the infinite mystery of nature’s recurring sleep that swallows
up the littleness of man in its immensity. I remember, too, a little picture of
darkened earth and rather turbulent dark sky in which a large boulder alone
glistens in the fading light—a rock of illumination and strength in the
surrounding uncertainty of gathering night. Brimming over with the
suggestion of an elevated melancholy sustained by faith, and painted with
an extraordinary earnestness of simple and direct conviction, it seems like a
symbol of Wyant’s own art life.
But almost everything that he painted is expressive of some phase, at
least, of himself. His work is more than ordinarily personal; perhaps, for the
reason already mentioned, that he so deliberately concentrated his motives.
And the quality of his poetry was lyrical. I have seen it called idyllic, but
that is to miss its higher and deeper qualities. The idyl, Tennyson
notwithstanding, is too much identified with the little pastoral poem, that
breathes the simple gladsomeness of the meadows; but a more serious strain
is interwoven with the gentleness and lovableness of Wyant’s muse. He was
passionately fond of music and, before his illness, could play the violin, not
learnedly, but with true feeling. And the music of his painting is that of the
violin; tenderly vibrating, searching home to one’s heart, by turns
lightsome, melancholy, caressing, impetuous, but with a tenderness in all.
He did not play on many colours, but reaches a subtlety of tone, often as
bewildering as it is soothing. The bewilderment will be aroused as much by
his shadowed foregrounds as
From the collection of George A. Hearn, Esq.

MOONLIGHT AND FROST.


By Alexander H. Wyant.
by the faintly luminous sky. They defy analysis and are triumphs of
impressionism. Impressionism of the true kind, I mean, pregnant with
suggestion and divested of aught that would clog its directness; exhibiting,
not knowledge, but the fruit of knowledge, and especially its tact of
omission. To the careless and commonplace eye his landscapes have
“nothing to them”; approached with a little understanding they mean so
much, and the measure of their meaning is the technical knowledge
involved. If there were any doubt of this, it could be disposed of by an
examination of his earlier work, in which he lets one into the secret of his
love of form and construction. Admirably sure and full of character is the
drawing of the ground and its features, bit by bit receiving its due share of
individuality; so also with the trees and their anatomy of trunk and
branches, and with the structure of the sky. Everything has been studied, so
that later out of the abundance of his technical skill he could be
significantly spontaneous. Yet increase of facility did not lessen the self-
exacting conscientiousness of his work. Some of his most impressionistic
pictures were the result of trying to reach a fuller exactness of expression;
when, finding confusion growing, he would seize another canvas and return
to the simplicity of his original thought and let it form itself. Few painters
are better represented in their extant works. The fumbled canvas, or the one
that, however sketchily, did not attain to his intention, never left the studio,
and after his death, Mrs. Wyant, with a fine regard for his memory and with
honour to herself, destroyed them. So the real Wyants—for I am told there
are sham ones on the market—are invariably worthy.
So truly did he retain the spirit of the student that it was not until a little
before his death that he allowed himself to feel that he had mastered the
grammar of his technique. Then, with the consciousness of his end before
him, he would exclaim, “Had I but five years more in which to paint, even
one year, I think I could do the thing that I long to.” Brave, modest soul!
What he might then have done we shall never know; but what he did do we
know to be very good. For another nature poet of our race, of like simplicity
and singleness of love for nature, of as choice and elevated a spirit, and as
lyrical in expression, we must go back to Wordsworth, who also in his
communings with nature found her message—

“Of truth, of grandeur, beauty, love, and hope,


And melancholy fear subdued by faith,
Of blessed consolations in distress,
Of moral strength and intellectual power,
Of joy in widest commonalty spread.”
XI

DWIGHT W. TRYON

I F we wished to introduce a foreigner to what is most distinctively


American in our painting, we should show him, I think, the work of some
of our marine and landscape painters. He would be least likely in these to
detect the influence of Europe. The point of view he would recognize, no
doubt, as the one common to all nature students since the Dutchmen of the
seventeenth century; but in regard to the technique he could not attribute its
character to the influence of this or the other master abroad, for our
landscape painters, like most other true students of nature, have found, each
for himself, their own necessary and inevitable language of expression.
Necessary because it originated in their own peculiar need, and inevitable
because it grew out of the particular character of the portion of nature that
they studied. And in most cases it is some phase of the American landscape
that has engaged the American painter, which accounts in no slight degree
for the individuality of his work.
For do we pay enough heed to the essential differences that nature
presents in different localities? At the moment I am not thinking of the
variations in construction, forms, and configuration, as, for example,
between the aspects of mountains and of simple pastoral regions, nor even
of the separateness of impress set upon the landscape by man in the
character of his buildings or of his farming occupations, but of that more
subtle difference produced by varying kinds of atmosphere. The great
landscape painters, we may have noticed, all belong to northern countries,
who have lived, comparatively speaking, within the same degrees of
latitude; and yet the landscapes of Holland, France, Scotland, England,
Norway, and America can never be mistaken for one another. Apart from
local conditions of man’s handiwork, each varies in the local quality of its
atmosphere—its degree of clarity or humidity, of briskness or
caressingness.
In a country vast as ours, there must needs be diversity in different parts,
so there cannot be any one character of landscape distinctively American;
but, in their faithful rendering of the local character, all may be
distinguishable from those of other countries. And this expression on the
countenance of nature is not unlike that on the face of a man or woman; the
painter may suggest it perfunctorily, or he may render it with a
completeness of sympathy and understanding, products of alert sensibility
and interested acquaintanceship. It is the evidence of these qualities that
gives enduring charm to Tryon’s landscapes.
No one who knows his work will need to be told that he is a New
Englander. His landscapes show an intimacy of knowledge of that locality,
and an affectionate sympathy with its particular phases of expression, that
could only result from the painter having grown up in that part, the boy’s
associations gradually maturing into the man’s convictions. His home was
in Hartford, Conn., where he was born in 1849. He entered upon life as a
stationer’s assistant, and pursued the occupation until he had accumulated
sufficient means to visit Paris, all the while spending his leisure time in
studying from nature and in discovering for himself how to represent his
ideas in paint. There is evidence in this of sanity as well as earnestness, of a
fine poise of character, qualities later to appear in his landscapes.
Above all, there is the perfectly natural process of a painter’s evolution; I
mean, the antecedent love of nature, the clear apprehension of the kind of
nature that he aimed to paint, the love of it and the knowledge preceding the
final acquisition of technique; meanwhile, the gradual upbuilding of
personal character by the discipline of postponing his ideals. So, when he
reached Paris, it was not as a raw, enthusiastic student whose subsequent
career spun suspended upon a mere cobweb of his fancy. He had married,
and took his wife with him, establishing a little home and having clear plans
in view, being, in fact, a man. He painted under Harpignies and Daubigny,
an excellent combination of influences, mutually complementary: the one
so sound and methodical, if a little prosaic; the other so captivating in the
perennial boyishness of his mind, so lovable a student of the simple
loveliness of rural scenes. What a happy antidote was Daubigny to the
excessive earnestness of a typical New England character; how persuasively
suggestive must his landscapes have been to one whose heart was implanted
in the austerer charms of his New England home. The influence of his two
masters served on the one hand to send the roots of his growth farther down
and to stiffen the trunk, and on the other to encourage a more abundant
leafage and the added fragrance of blossom. From both, also, he must have
gained a store of technical principles; but of direct influence in his manner
of painting there is no trace. His own special problem was one different
from theirs, and he had to find his own way of solving it.
Even in one of his earliest landscapes painted about 1881, after his return
from Paris, from studies made abroad, there is a decisively individual note.
It is a scene of ploughing, owned by Mr. Montross—a stretch of dark rich
soil, with man and horses pushing the furrow toward a clear, cool horizon.
There is a larger feeling than Daubigny would have portrayed; a sterner
one, if you will, certainly one more bracing in its suggestion of vigorous
earth and breezy sky, and more distinctly inspired than Harpignies could
have made it, with the sentiment of the soil and sky in their relation to the
life of man. Still, the motive of the picture is so far a borrowed one that,
although it has the feeling of a New England scene, it has not its local
characteristics of atmosphere or of soil colour, lacking the more sensitive
quality of the one, and the tenderer hues of the other. While, then, this
picture is without the subtle qualities that mark the later ones, it has a clear,
strong note of vigorous earnestness, strongly felt and strongly realized.
Indeed, it seems entirely characteristic of the strength of purpose and sturdy
qualities which are the foundation of Tryon’s equipment, both as a man and
a painter. He seems to have grown up with the smell of the soil in his
nostrils as Millet did, though without the latter’s saddened associations; to
have been nourished with the brisk New England air, and to have gathered
muscle over its ploughed and grassy uplands. The keen stimulus of nature
went through and through him early and has stayed with him, so that his art
partakes of its strength. In his pictures, one finds, I think, a stronger
foundation than only that of good drawing and construction; an earnest,
wholesome delight in the strength of nature as being something in which he
himself shares; which, indeed, has so grown into his mind and life that its
expression in his work is but a matter of course. It is a part of his most
serious convictions, so that his rendering of it is convincing.
Put into words, the distinction may seem a little fine drawn; but I feel
sure that our experience of pictures gives it substance. How often, for
example, in the work of the French classicists we may see illustrations of
human vigour, on which good drawing and construction have been
expended, and yet their suggestion of vigour is only an affectation; a quality
aimed at by the painter, but not vitalized by strong, earnest convictions of
his own. What a protestation of strength there is in Salvator Rosa’s
landscapes, and how little real convincingness! And, coming to the
landscapes of our own time, it would be easy to quote examples of strong
drawing and construction from which,

From the collection of Charles L. Freer, Esq.

SPRING BLOSSOMS.
By Dwight W. Tryon.
From the collection of Charles L. Freer, Esq.
EARLY SPRING, NEW ENGLAND.
By Dwight W. Tryon.
however, the spirit of strength is lacking. They are the work of men who
mean strongly, but are not themselves strong men. So surely does personal
character, or lack of it, show in a painter’s work, not the mere
robustiousness of personal force, but the settled, earnest, habitual
convictions that are the elements of character. And quite as evident to our
experience in pictures is the distinction between the real and the false in
refinement. Mere subtlety of brush work, while it may create for a while an
illusion of refinement, will not satisfy us in the long run.
Many of Tryon’s landscapes reach a pitch of delicate suggestion in the
rendering of soft air, caressing atmosphere, and shrouded light that is
unsurpassed by any painter in this country; for the impression is much
deeper than that of an entrancing skill in the management of the pigments.
The spirit of the landscape stole into his heart when a boy, and has abided
with him in his manhood; he is so much a child of New England, sweetened
by its tenderer influences as well as nurtured on its hardihood, that, sharing
its strength and refinement, he gives expression to himself when he
reproduces these qualities in his pictures. Hence, in both directions, their
complete convincingness. A fact, too, which helps to justify this
appreciation is that his pictures show an interest in so many moods of the
landscape, and the degree of force or of subtlety with which he renders each
is regulated by the demand of the occasion. You cannot divide the past
twenty years of his productiveness into special periods of style; any attempt
to do so will bring you up against the insurmountable objection of finding
that two canvases of very different feeling and manner of painting are dated
the same year. Development, necessarily, there has been in style; increased
acquisition of facility and the power to render more penetratingly the mood
of nature he is studying. But evolution of motive you will scarcely find.
That from the first has been realistic; in the sense that the landscape, as it
appears to him to be, affords primarily sufficient incentive to his study.
In the presence of nature he makes studies, intent for the time being
solely on recording what he sees; later, in his New York studio, the poetic
suggestion of these studies will come to him, and he composes a picture.
But the process is from realism to poetry, and not contrariwise, as one
suspects to be the case in the poetical landscapes of some painters. Tryon’s
way is not unlike a man’s regard for a good mother. In the days of his
habitual intercourse with her, it is her dignity and sweetness that grow into
his life, the changes of expression in her face and voice that win upon his
devotion, her beautiful reasonableness that is accepted as quite a natural
thing. It is only when the son’s life is drawn apart from the habit of her
presence that the sentiment of a mother’s love is realized. So Tryon’s
withdrawals to city life allow the poetry of nature to steal in upon his
imagination; when he resumes his face-to-face communing with it, the life
habit of absorbed regard comes back to him. The result of this is that the
sentiment of his pictures grows out of the actual, and represents the soul of
a fact. One finds one’s self admiring the extraordinary truth of the visual
impression, and then often surprised that material so homely should yield
such abundance of poetic suggestion; forgetting, for the moment, that
poetry is not an element of nature, but a quality of the painter’s mind,
representing the degree of sincerity and elevation of purpose with which he
has approached his subject. Tryon’s poetry comes of the associations
garnered through a life of affectionate intimacy with the country of his
birth. It is as true and spontaneous as filial love.
His technical skill has secured the respect and admiration of his fellow-
painters. They assign him that final title of approval, “a painter’s painter;”
meaning that only those who know by practical experience the difficulties
and trials of technique can properly appreciate his ability and
resourcefulness, and certainly not implying, as is sometimes the case when
this expression is used, that the admirable qualities in the picture are
primarily and solely technical ones.
Attempting in non-painter language to summarize the spirit of his
method, one may, perhaps, reduce it to the equivalent elements in his own
character—poise and sympathetic penetration. The balanced effect of his
landscapes is very notable: a harmony of colour in which there is no jar, a
similar equipoise in the details introduced, a delicate adjustment of strength
and tenderness and of sentiment to facts; an ensemble of uninterrupted
unity. In the matter of sympathetic penetration—a rather clumsy expression
for which I can find no happy alternative—his method is even more
remarkable. I allude to the affectionate studiousness with which he analyzes
the significant constituents of the landscape, and to the degree in which his
eye penetrates the secret of the envelope of atmosphere, of that particular
quality of atmosphere characteristic of New England.
I would cite the “Early Spring, New England,” not as an example of one
of his most beautiful landscapes, but as a triumph of technical resource, to
which was awarded the gold medal in 1898 at the Carnegie exhibition in
Pittsburg. The foreground is a pasture with a brook winding through it, and
several leafless trees which spread their delicate network of branches
against a clear, open sky that reddens slightly near the horizon. Beyond is
cultivated land, partly covered with the brilliant green of young vegetation,
and partly red, upturned soil, with a team ploughing. Farther back are gently
rising hills.
The front of the picture is painted with remarkably delicate detail, and in
the distant parts there is a similar suggestion conveyed of the worthiness of
the scene to be minutely studied. There is not a square inch in the
composition that is without individual interest, and yet this elaborate mosaic
unifies into a single impression of spaciousness; for the relative significance
of each plane in the picture has been so shrewdly realized. The eye is
invited to travel back to the remotest part of the ground and up into the
expanse of sky. This is the primary invitation of the picture as would be that
of the actual scene; and then follows, if you have eyes for it, the beckoning
in this and that direction to the separate interest of the various parts. This
accurate rendering of the effect of intervening atmosphere upon the
receding forms and colours brings the atmosphere itself into the picture; a
softly stealing animation, not yet nimble, but gently quickening into life. It
is, indeed, a picture of quite extraordinary subtlety; and so much the more a
triumph of accomplishment because it is a very large one, and the mere
problem of filling such an extent of canvas with the evidences of minute
observation, so that it should still hold well together, was a most formidable
one. There was no possibility of evasion or of falling back upon convenient
generalizations: the problem, once grasped, had to be solved to its ultimate
conclusion.
Yet the very magnitude of canvas and of problem impairs somewhat the
intimacy of feeling in the picture, and for all its abounding skill we shall not
reckon it among Tryon’s choicest work. In that he gives us, when he wills,
the sense of spaciousness within a much smaller frame, and, compassing it
around so discreetly, makes its subtle appeal by so much the more
insinuating. These comparatively smaller pictures are too numerous and
different in character to allow of detailed allusion, yet one may single out a
few such gems as “The Rising Moon” and “Sunrise,” owned by Mr. Charles
L. Freer; “After Showers—June,” owned by Colonel Frank J. Hecker; “The
Meadow—Evening,” owned by Mr. A. T. Sanders; “Springtime,” owned by
Mr. George
From the collection of J. J. Albright, Esq.

EVENING—AUTUMN.
By Dwight W. Tryon.
A. Hearn; and a “Winter Evening” and “Early Spring,” the property of
Mr. N. E. Montross.
These are masterpieces,—and the list is incomplete,—pictures that you
may study from the strictest standpoint of technical excellence, and that
exert an influence upon the imagination which one may believe will be felt
by those who come after us as fully as by ourselves.
In considering American landscapes, there is more than a little tendency
to dwell upon the names of the painters who are dead, regardless of the fact
that the traditions which they established are being maintained. Among
those who are maintaining them, Tryon is conspicuous, and in a way that is,
perhaps, more distinctive than theirs. He represents much more closely the
kind of contribution that the American temperament may be expected to
make to the progress of painting. For unless painting can continue to reflect
the evolution of human progress, it is, after all, only a “dead language.” But
it is landscapes such as Tryon’s that prove its vitality. They represent the
combination of qualities that differentiate American civilization in its
worthiest form from that of other countries and of past times. They combine
a largeness of outlook with alert sensibility to impressions; being, at once,
big in character and minutely subtle.
XII

HORATIO WALKER

U PON his first appearance last year as a contributor to the exhibition of


the British Institute of Water Colours, Horatio Walker’s picture, “The
Potato Pickers,” was prominently hung, and he himself was elected a
member. Considering the fine record of the Institute and its high rank
among water colour societies, such instant recognition of a newcomer was
very notable.
But it is just the way in which an artist of Walker’s calibre is likely to
make his impression—at once and authoritatively; for he is a painter of
unusual personal force, and of a persuasiveness quite as remarkable,
qualities not always found in combination, but, when united, irresistible.
And these artistic qualities are the counterparts of similar elements in his
character as a man. His is a forceful personality of moral as well as mental
force. How much this means! There is a kind of forceful person who slaps
you on the back in the street, and you probably consider him a nuisance;
and there is a kind of painter who would violently arrest your attention by
the bravery of his brush strokes or some surprising crash of colour scheme
or chiaroscuro.
In such forcefulness there is a certain effrontery that one resents at once;
or which, if it arouse a little momentary curiosity or even interest, will in
the long run be followed by intolerable weariness. For it is almost entirely a
mere display of manual gymnastics, an exploitation of self. There may be a
little mind behind it, but it will be the quality of mind that is simply of the
active kind, enamoured of its own activity. It is not regulated by the moral
sense, responsible to self-control, contributory to some serious and
absorbing purpose, involving a realization of the intense meaningfulness of
nature and life. This is the foundation quality of what is big in life and art: a
noble seriousness that penetrates the facts, and lifts them upon the elevation
of its own spirit to the dignity of what is grandest and most abiding in the
universal scheme.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

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


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

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


personal growth every day!

ebookbell.com

You might also like