Java Programming Exercises Volume One Language Fundamentals And Core Concepts Christian Ullenboom instant download
Java Programming Exercises Volume One Language Fundamentals And Core Concepts Christian Ullenboom instant download
https://ebookbell.com/product/java-programming-exercises-volume-
one-language-fundamentals-and-core-concepts-christian-
ullenboom-58439770
https://ebookbell.com/product/java-programming-exercises-volume-one-
language-fundamentals-and-core-concepts-1st-edition-christian-
ullenboom-58435736
https://ebookbell.com/product/java-programming-exercises-volume-one-
language-fundamentals-and-core-concepts-ullenboom-58637136
https://ebookbell.com/product/java-programming-exercises-volume-two-
java-standard-library-christian-ullenboom-58439762
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
https://ebookbell.com/product/java-programming-pandey-hari-
mohan-21999882
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:
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
©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.
DOI: 10.1201/9781003454502
Typeset in Times
by codeMantra
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
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
4 Arrays 86
Everything Has a Type 86
Quiz: Array Types ⭑ 86
One‑Dimensional Arrays 87
viii Contents
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:
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.
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.
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.
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
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
6 DOI: 10.1201/9781003454502-2
1 • Introduction to the Java Ecosystem 7
$ javac Application.java
$ 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?
• 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:
Task:
SUGGESTED SOLUTIONS
• 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
• 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.
DOI: 10.1201/9781003454502-3 9
10 Java Programming Exercises
Task:
Task:
• 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>
• 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
• 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.
• 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:
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.
• 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:
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:
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.
Task:
Task:
Example:
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***!".
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
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
if ( true ) {
if ( false )
if ( 3!=4 )
;
else
System.out.println( "ship's kobold" );
else
System.out.println( "Pumuckl" );
}
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?
• 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
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.
The following vector graphic in SVG rotates a rectangle around the center point (100, 100), by 60
degrees:
Task:
• Write a program that rotates 36 SVG rectangles 10 degrees on top of each other and outputs
them to the screen.
Example:
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
Task:
• Create an SVG output on the command line with 50 circles side by side.
Task:
Example:
12
3
‑1
0
Sum: 14
• 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:
B:
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:
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
Task:
Examples:
• 12345 → 1, 5
• 987654 → 4, 9
• 11111 → 1, 1
• 0 → 0, 0
• ‑23456788888234567L → 2, 8
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
1. Syntactic errors.
2. Semantic errors.
3. Style guide violations.
Task:
Optional: The output should appear as a tree, in the sense that all lines are centered.
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
_#_#_#_#_#
#_#_#_#_#_
_#_#_#_#_#
#_#_#_#_#_
_#_#_#_#_#
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:
><> <><
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:
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:
• 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
• 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
• 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
WESTCHESTER HILLS.
By Homer D. Martin.
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
ALEXANDER H. WYANT
DWIGHT W. TRYON
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
ebookbell.com