SlideShare a Scribd company logo
Java 9 Recipes A Problemsolution Approach 3rd Ed
Juneau Josh download
https://ebookbell.com/product/java-9-recipes-a-problemsolution-
approach-3rd-ed-juneau-josh-55586392
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 9 Recipes A Problemsolution Approach Josh Juneau
https://ebookbell.com/product/java-9-recipes-a-problemsolution-
approach-josh-juneau-5857764
Modern Java Recipes Simple Solutions To Difficult Problems In Java 8
And 9 Ken Kousen
https://ebookbell.com/product/modern-java-recipes-simple-solutions-to-
difficult-problems-in-java-8-and-9-ken-kousen-6732954
Java 9 Modularity Revealed Project Jigsaw And Scalable Java
Applications 1st Ed Alexandru Jecan
https://ebookbell.com/product/java-9-modularity-revealed-project-
jigsaw-and-scalable-java-applications-1st-ed-alexandru-jecan-55591686
Java 9 Dependency Injection Write Loosely Coupled Code With Spring 5
And Guice Patel
https://ebookbell.com/product/java-9-dependency-injection-write-
loosely-coupled-code-with-spring-5-and-guice-patel-56225262
Java 9 Revealed For Early Adoption And Migration Sharan Kishori
https://ebookbell.com/product/java-9-revealed-for-early-adoption-and-
migration-sharan-kishori-22038542
Java 9 Data Structures And Algorithms Debasish Ray Chawdhuri
https://ebookbell.com/product/java-9-data-structures-and-algorithms-
debasish-ray-chawdhuri-24542320
Java 9 Modularity Patterns And Practices For Developing Maintainable
Applications Paul Bakker
https://ebookbell.com/product/java-9-modularity-patterns-and-
practices-for-developing-maintainable-applications-paul-bakker-5903132
Java 9 Modularity Patterns And Practices For Developing Maintainable
Applications 1st Edition Sander Mak
https://ebookbell.com/product/java-9-modularity-patterns-and-
practices-for-developing-maintainable-applications-1st-edition-sander-
mak-6718992
Java 9 Modularity Revealed Project Jigsaw And Scalable Java
Applications Alexandru Jecan
https://ebookbell.com/product/java-9-modularity-revealed-project-
jigsaw-and-scalable-java-applications-alexandru-jecan-6724108
Java 9 Recipes A Problemsolution Approach 3rd Ed Juneau Josh
Java 9 Recipes
A Problem-Solution Approach
Third Edition
Josh Juneau
Java 9 Recipes: A Problem-Solution Approach
Josh Juneau							
Hinckley, Illinois, USA						
ISBN-13 (pbk): 978-1-4842-1975-1		 ISBN-13 (electronic): 978-1-4842-1976-8
DOI 10.1007/978-1-4842-1976-8
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484219751. For more
detailed information, please visit http://www.apress.com/source-code.
Library of Congress Control Number: 2017943502
Copyright © 2017 by Josh Juneau
Contents at a Glance
About the Author�������������������������������������������������������������������������������������������������� xliii
About the Technical Reviewer��������������������������������������������������������������������������������xlv
Acknowledgments������������������������������������������������������������������������������������������������xlvii
Introduction�����������������������������������������������������������������������������������������������������������xlix
■
■Chapter 1: Getting Started with Java 9����������������������������������������������������������������� 1
■
■Chapter 2: Java 9 Enhancements������������������������������������������������������������������������ 35
■
■Chapter 3: Strings����������������������������������������������������������������������������������������������� 47
■
■Chapter 4: Numbers and Dates���������������������������������������������������������������������������� 65
■
■Chapter 5: Object-Oriented Java������������������������������������������������������������������������� 99
■
■Chapter 6: Lambda Expressions������������������������������������������������������������������������ 137
■
■Chapter 7: Data Sources and Collections���������������������������������������������������������� 159
■
■Chapter 8: Input and Output������������������������������������������������������������������������������ 195
■
■Chapter 9: Exceptions and Logging������������������������������������������������������������������� 221
■
■Chapter 10: Concurrency����������������������������������������������������������������������������������� 239
■
■Chapter 11: Debugging and Unit Testing����������������������������������������������������������� 267
■
■Chapter 12: Unicode, Internationalization, and Currency Codes����������������������� 285
■
■Chapter 13: Working with Databases���������������������������������������������������������������� 305
■
■Chapter 14: JavaFX Fundamentals�������������������������������������������������������������������� 355
■
■Chapter 15: Graphics with JavaFX�������������������������������������������������������������������� 429
■
■Chapter 16: Media with JavaFX������������������������������������������������������������������������� 471
■
■Chapter 17: Java Web Applications with JavaServer Faces������������������������������ 499
■
■Chapter 18: Nashorn and Scripting������������������������������������������������������������������� 529
■
■Chapter 19: E-mail��������������������������������������������������������������������������������������������� 553
■
■Chapter 20: JSON and XML Processing������������������������������������������������������������� 563
■
■Chapter 21: Networking������������������������������������������������������������������������������������ 585
■
■Chapter 22: Java Modularity����������������������������������������������������������������������������� 605
Index��������������������������������������������������������������������������������������������������������������������� 615
Introduction
The Java programming language was introduced in 1995 by Sun Microsystems. Derived from languages such
as C and C++, Java was designed to be more intuitive and easier to use than older languages, specifically due
to its simplistic object model and automated facilities such as memory management. At the time, Java drew
the interest of developers because of its object-oriented, concurrent architecture; its excellent security and
scalability; and because applications developed in the Java language could run on any operating system
that contained a Java Virtual Machine (JVM). Since its inception, Java has been described as a language that
allows developers to “write once, run everywhere” as code is compiled into class files that contain bytecode,
and the resulting class files can run on any compliant JVM. This concept made Java an immediate success
for desktop development, which later branched off into different technological solutions over the years,
including development of web-based applications and rich Internet applications (RIAs). Today, Java is
deployed on a broad range of devices, including mobile phones, printers, medical devices, Blu-ray players,
and so on.
The Java platform consists of a hierarchy of components, starting with the Java Development Kit (JDK),
which is composed of the Java Runtime Environment (JRE), the Java programming language, and platform
tools that are necessary to develop and run Java applications. The JRE contains the JVM, plus the Java
application programming interfaces (APIs) and libraries that assist in the development of Java applications.
The JVM is the base upon which compiled Java class files run and is responsible for interpreting compiled
Java classes and executing the code. Every operating system that is capable of running Java code has its
own version of the JVM. To that end, the JRE must be installed on any system that will be running local
Java desktop or stand-alone Java applications. Oracle provides JRE implementations for most of the major
operating systems. Each operating system can have its own flavor of the JRE. For instance, mobile devices
can run a scaled-down version of the full JRE that is optimized to run Java Mobile Edition (ME) and Java SE
embedded applications. The Java platform APIs and libraries are a collection of predefined classes that are
used by all Java applications. Any application that runs on the JVM makes uses the Java platform APIs and
libraries. This allows applications to use the functionality that has been predefined and loaded into the JVM
and leaves developers with more time to worry about the details of their specific application. The classes
that comprise the Java platform APIs and libraries allow Java applications to use one set of classes in order
to communicate with the underlying operating system. As such, the Java platform takes care of interpreting
the set of instructions provided by a Java application into operating system commands that are required for
the machine on which the application is being executed. This creates a facade for Java developers to write
code against so that they can develop applications that can be written once and run on every machine that
contains a relevant JVM.
The JVM and the Java platform APIs and libraries play key roles in the life cycle of every Java application.
Entire books have been written to explore the platform and JVM. This book focuses on the Java language
itself, which is used to develop Java applications, although the JVM and Java platform APIs and libraries are
referenced as needed. The Java language is a robust, secure, and modern object-oriented language that can
be used to develop applications to run on the JVM. The Java programming language has been refined over
several iterations and it becomes more powerful, secure, and modern with each new release. This book
covers many features of the Java programming language from those that were introduced in Java 1.0 through
those that made their way into the language in Java 9. In 2014, Oracle Corporation released Java 8, which
was another milestone release for the Java ecosystem. Not only was Java already the most modern, statically
■ Introduction
l
typed, object-oriented language available for development, but Java 8 added important new enhancements
to the language, such as lambda expressions, streams processing, and default methods. JavaFX 8 was also
released at the same time, advancing desktop Java applications more than ever. JavaFX 8 can be used for
developing rich desktop and Internet applications using the Java language, or any other language that runs
on the JVM. It provides a rich set of graphical and media user interfaces to develop extraordinary visual
applications. This release is another nice update to the JavaFX platform, adding in features such as the
Swing node and the Print API. In 2017, Java 9 is released, enhancing the platform with features such as
modularity, an updated Process API, and jShell. This book covers the fundamentals of Java development,
such as installing the JDK, writing classes, and running applications. It delves into essential topics such
as the development of object-oriented constructs, exception handling, unit testing, and localization. The
book also provides solutions for desktop application development using the JavaFX, and some web-based
and database solutions. It covers JavaFX in depth and is an essential guide for developers beginning to
use JavaFX 8+. This book can be used as a guide for solving problems that ordinary Java developers may
encounter at some point. A broad range of topics is discussed, and the solutions to the problems that are
covered in this book are concise and to the point. If you are a novice Java developer, we hope that this
book will help you get started on your journey to working with one of the most advanced and widely used
programming languages available today. For those of you who have used the Java language for some time,
we hope that this book will provide you with updated material that is new to Java 9, JavaFX, and even some
Java web development so that you can further refine your Java development skills. I ensure that advanced
Java application developers will also learn a thing or two regarding the new features of the language and
perhaps even stumble upon some techniques that were not used in the past. Whatever your skill level, this
book is good to have close at hand as a reference for solutions to those problems that you encounter in your
daily programming.
Who This Book Is For
This book is intended for all those who are interested in learning the Java programming language and/or
already know the language but would like some information regarding the new features included in Java
SE 9 and JavaFX. Those who have not yet programmed in the Java language can read this book, and it will
allow them to start from scratch to get up and running quickly. Intermediate and advanced Java developers
who are looking to update their arsenal with the latest features that Java SE 9 makes available to them can
also read the book to quickly update and refresh their skill set. Java desktop programmers will find this book
useful for its content on developing desktop applications using the JavaFX API. There is, of course, a myriad
of other essential topics that will be useful to Java developers of any type.
How This Book Is Structured
This book is structured such that it does not have to be read from cover to cover. In fact, it is structured
so that developers can chose which topics they wish to read about and jump right to them. Each recipe
contains a problem to solve, one or more solutions to solve that problem, and a detailed explanation of
how the solution works. Although some recipes may build upon concepts that have been discussed in other
recipes, they contain the appropriate references so that the developer can find other related recipes that are
beneficial to the solution. The book is designed to allow developers to get up and running quickly with a
solution so that they can be home in time for dinner.
1
© Josh Juneau 2017
J. Juneau, Java 9 Recipes, DOI 10.1007/978-1-4842-1976-8_1
CHAPTER 1
Getting Started with Java 9
In this chapter we present a handful of recipes to help programmers who are new to the Java language, as
well as those having experience in other languages, become accustomed to Java 9. You will learn to install
Java, and also install an Integrated Development Environment (IDE) from which you’ll develop applications
and experiment with the solutions provided in this book. You will learn basics of Java such as how to create
a class and how to accept keyboard input. Documentation is often overlooked, but in this chapter you will
quickly learn how to create great documentation for your Java code.
■
■ Note Java 9 Recipes is not intended as a complete tutorial. Rather, it covers key concepts of the Java
language. If you are truly new to Java, we recommend buying and reading one of the many Beginning Java
books that are also published by Apress.
1-1. Creating a Development Environment
Problem
You want to install Java and experiment with the language. You’d also like a reasonable IDE to use with it.
Solution
Install Java Development Kit 9 (JDK. That gives you the language and a compiler. Then install the NetBeans
IDE to provide a more productive working environment.
Java Standard Edition (Java SE) is sufficient for most recipes in this book. To download the release, visit
the following page on the Oracle Technology Network (OTN):
http://www.oracle.com/technetwork/java/javase/overview/index.html
Figure 1-1 shows the Downloads tab, and you can see the Java Platform download link and image
prominently on the page. Next to that link is an image for the NetBeans IDE, which provides the option of
downloading the JDK and NetBeans together. Choose the option that you prefer, download the release for
your platform, and run the setup wizard to install. For the purposes of this book, I am using NetBeans IDE 8.2.
Chapter 1 ■ Getting Started with Java 9
2
■
■ Note If you chose to only install the Java Platform (JDK) and not NetBeans, you can download NetBeans at
a later time by visiting netbeans.org.
How It Works
The name Java™ is a trademark owned by Oracle Corporation. The language itself is open source, and its
evolution is controlled by a process known as the Java Community Process (JCP). You can read more about
that process at www.jcp.org.
While the language is not owned per se by Oracle Corporation, its core development tends to be steered
by that company. It is Oracle Corporation that runs the JCP, and that owns the jcp.org domain.
There are many editions of Java, such as the Mobile Edition (ME) and the Enterprise Edition (EE). Java
SE is the Standard Edition and represents the heart of the language. We’ve built the recipes in this book for
Java SE programmers. Those interested in the development of embedded applications for devices such as
Raspberry Pi may be interested in learning more about Java ME. Similarly, those interested in developing
web applications and working with enterprise solutions may be interested in learning more about Java EE.
■
■ Note Enterprise developers may want to buy and read a copy of Java EE 7 Recipes by Josh Juneau
(Apress, 2013).
There are several good websites that you can visit to learn more about Java and keep up to date with the
latest on the platform. A good place to begin for all things Java is the following page on the OTN:
http://www.oracle.com/technetwork/java/index.html
Figure 1-1. Java SE Downloads page on the OTN
Chapter 1 ■ Getting Started with Java 9
3
The wealth of resources available from this page can be overwhelming at first, but it’s worth your time to
look around and get passingly familiar with the many links that are available.
One of the links will be to Java SE, which takes you to the page shown earlier in Figure 1-1. It is from
there that you can download Java SE and the NetBeans IDE. Also from there you have access to the official
documentation, to community resources such as forums and newsletters, and to training resources designed
to help you build knowledge in Java and become certified in the language.
1-2. Getting to “Hello, World”
Problem
You’ve installed Java SE 9 and the NetBeans IDE. Now you want to run a simple Java program to verify that
your installation is working properly.
Solution
Begin by opening the NetBeans IDE. You should see a workspace resembling the one in Figure 1-2. You may
see some projects in the left-hand pane if you’ve already been working on projects within the IDE.
Figure 1-2. Opening the NetBeans IDE
Chapter 1 ■ Getting Started with Java 9
4
Go to the File menu and select New Project. You’ll see the dialog in Figure 1-3. Choose the Java category,
and then Java Application. Click Next to advance to the dialog shown in Figure 1-4.
Figure 1-3. Creating a new Java SE project
Chapter 1 ■ Getting Started with Java 9
5
Give your project a name. For the project related to this book, use the name Java9Recipes. Enter the
project name into the Project Name text box at the top of the dialog in Figure 1-4.
Then specify the name of your main class in the Create Main Class text box. Give the following name:
org.java9recipes.chapter01.recipe1_02.HelloWorld
Be sure to that you’ve entered the project name and class name just as we provide them here,
because the code to follow depends upon your doing so. Make sure the “Project Name” text box specifies
Java9Recipes. Make sure the “Create Main Class” text box specifies org.java9recipes.chapter01.
recipe1_02.HelloWorld.
■
■ Tip Pay attention to case; Java is case-sensitive.
Press “Finish” to complete the wizard and create a skeleton project. You should now be looking at a Java
source file. Skeleton code is generated for you, and your NetBeans IDE window should resemble the one in
Figure 1-5.
Figure 1-4. Naming the project
Chapter 1 ■ Getting Started with Java 9
6
Place your cursor anywhere in the source code pane. Press Ctrl-A to select all the skeleton code. Then
press Delete to get rid of it. Replace the deleted code with that from Listing 1-1.
You can find the code in Listing 1-1 as part of our example download for the book. There are two files named
HelloMessage.java and HelloWorld.java, which reside in a Java package named org.java9recipes.chapter01.
recipe1_02. Note that all recipe solutions of substance throughout this book are in that example download.
The first class, HelloMessage, is a container class that is used to hold a String-based message.
Listing 1-1. A “Hello, World” Example
package org.java9recipes.chapter01.recipe1_02;
public class HelloMessage {
    private String message = ;
    public HelloMessage() {
        this.message = Default Message;
    }
    public void setMessage (String m) {
        this.message = m;
    }
    public String getMessage () {
        return message.toUpperCase();
    }   
}
The next class is named HelloWorld, and it initiates the program:
public class HelloWorld {
    /* The main method begins in this class */
Figure 1-5. Viewing the skeleton code generated by NetBeans
Chapter 1 ■ Getting Started with Java 9
7
    public static void main(String[] args) {
        HelloMessage hm;     
        hm = new HelloMessage();
        System.out.println(hm.getMessage());
        hm.setMessage(Hello, World);
        System.out.println(hm.getMessage());    
    }
}
Make sure you have pasted (or typed) the code from Listing 1-1. Compile and run the program, and you
should see the following output:
run:
DEFAULT MESSAGE
HELLO, WORLD
BUILD SUCCESSFUL (total time: 1 second)
This output will appear in a new pane named “Output” that is opened by NetBeans at the bottom of the
IDE window.
How It Works
You can run almost all the solutions in this chapter using the same general technique shown in this recipe.
We’ve been painstakingly detailed for that reason, showing the step-by-step screenshots just this one time.
Packages
The solution example begins by creating a Java package:
package org.java9recipes.chapter01.recipe1_02;
Packages are a way of grouping related classes together into a shared namespace. The idea is to achieve
universal uniqueness by working your way down your organization’s domain name in reverse order. It is also
customary to write package names in all lowercase.
NetBeans will create a directory structure to imitate your package path. In this case, NetBeans created
the following directory path:
C:UsersJonathanGennickDocumentsNetBeansProjects
Java9Recipessrcorgjava9recipeschapter01recipe1_02
Following are some things to notice about this path:
• The front part is C:Users...NetBeansProjects. NetBeans creates all projects
under a NetbeansProject directory unless you specify otherwise, which you can do
from the dialog in Figure 1-4. Many developers specify shorter paths.
• Next is the first occurrence of Java9Recipes. This occurrence corresponds to the
project name you gave when you filled in the Project Name text box from Figure 1-4.
Chapter 1 ■ Getting Started with Java 9
8
• Any source files you create go into the src directory. NetBeans creates other
directories at this level. For example, NetBeans creates a build directory, and then
underneath it is a classes subdirectory to hold your compiled class files.
• Last are the directories mirroring the package path that you specify, in this case org
java9recipeschapter01recipe1_02. When you compile your code, an identical
structure is created under the buildclasses directory. Note that if using another
IDE, you may see differences in the directories that are created.
You do not need to explicitly create a package. If you do not create one, the Java compiler will create
one for you, and give it a name that is hidden from you. We prefer to be explicit, and you should too. Being
thoughtful and explicit about Java package names is de rigueur in the professional setting. Organization, as
well as judiciously chosen naming conventions, is important when developing any significant application.
JavaBeans-Style Classes
Next in the solution example you see a class definition following the JavaBeans pattern. The definition of
HelloMessage follows a pattern that you’ll encounter often in Java programming, and we include it for that
reason. The class is a simple one, capable of holding a single, String field named message.
Three methods are defined on the class:
HelloMessage(). This method, also known as the constructor, is named the
same as the class. In this case, it takes no arguments. It’s automatically invoked
whenever you create a new object of the class. Note that this is known as a
“no-arg” constructor because it is typed out within the class, and it takes no
arguments. If you do not supply a constructor, the JVM will supply a default
constructor (also takes no arguments) automatically.
setMessage(String). This accessor method begins with the word set. It takes
one parameter. It specifies the message to be returned by the corresponding get
method.
getMessage(). This accessor method returns the currently defined message. In
our example, we choose to uppercase the message.
■
■ Note Accessor methods are used in JavaBeans classes to access any privately declared class members.
In this case, the private variable identified as message can be accessed using these methods. Accessor methods
are more commonly referred to as “getters” and “setters.”
Methods beginning with set and get are termed as setter and getter methods. The variable message is
private to the class, which means you have no direct access to message from outside of the class.
You’ll see the keyword this used in the class. It is a special keyword in Java used to reference the
current object. Its use is redundant in Listing 1-1, but would be needed if any of the methods happened to
create variables of their own that were also named message. It is common practice to make use of the “this”
keyword to reference the class members from within the “getter” and “setter” methods.
It is common in Java to mediate access to class variables through setter and getter methods like those
in our example. Those methods represent a contract of sorts with other classes and your main program.
Their benefit is that you can change the storage implementation of HelloMessage however you like. Other
code that depends upon HelloMessage will continue to work properly so long as you maintain the external
behavior of setMessage() and getMessage().
Chapter 1 ■ Getting Started with Java 9
9
The Main Program
The incantation public static void main(...) is used from within a public class to denote the entry
point of a Java program. That declaration begins an executable method named main. You must specify one
parameter that is an array of Strings, and typically that parameter is defined as String[] args.
When you execute the currently selected class, NetBeans compiles the code to a set of binary files, and
then transfers control to the main() method. NetBeans can also be configured to recompile on save, which
would then cause the transfer of control to the main() method. That method, in turn, does the following:
1. Executes HelloMessage to create a variable named hm that is capable of holding
an instance of the class HelloMessage. The variable hm is empty at this point.
2. Invokes new HelloMessage() to create an object of the class by that name. The
no-argument constructor will be executed, and Default Message is now set as
the greeting text. The new object is now stored in the variable hm.
3. Makes a call to System.out.println() to show that the object’s no-argument
constructor has indeed executed as expected. The greeting DEFAULT MESSAGE
is displayed in the “Output” pane.
4. Sets the message to be the traditional text Hello, World.
5. Makes another call to System.out.println() to output the new message
that has just been set. Now you see the greeting HELLO, WORLD added to the
“Output” pane.
The pattern in the solution is common in Java programming. The main() method is where execution
begins. Variables are defined, and objects are created using the new operator. Object variables are often set
and retrieved using setter and getter methods.
■
■ Tip Command-line apps are passé. System administrators and programmers sometimes write them as
utilities, or to batch-process large amounts of data. But in the main, most of today’s applications are GUI applications.
JavaFX is the way forward in writing standard desktop applications, and you can learn about it in Chapters 14
through 16. Recipe 14-1 provides what is essentially a “Hello,World” application in GUI form. JavaEE offers options
for developing web-based applications for the Java Platform, and you can learn more about that in Chapter 17.
1-3. Configuring the CLASSPATH
Problem
You want to execute a Java program, or include an external Java library in the application you are executing.
Solution
Set the CLASSPATH variable equal to the directory location of the user-defined Java classes or Java Archive
(JAR) files that you need to have access to for executing your application. Let’s say that you have a directory
named JAVA_DEV located at the root of your OS drive, and all the files your applications needs to access are
located in this directory. If this is the case, then you would execute a command such as the following:
set CLASSPATH=C:JAVA_DEVsome-jar.jar
Chapter 1 ■ Getting Started with Java 9
10
Or on Unix and Linux systems:
export CLASSPATH=/JAVA_DEV/some-jar.jar
Alternately, the javac command provides an option for specifying the location of resources that need
to be loaded for an application. On all platforms, setting the CLASSPATH using this technique can be done via
the -classpath option as follows:
javac –classpath /JAVA_DEV/some-jar.jar
Of course, on Microsoft Windows machines the file path will use the backslash () instead.
■
■ Note The javac –cp option may be used, rather than specifying the –classpath option.
How It Works
Java implements the concept of a classpath. This is a directory search path that you can specify system-wide
using the CLASSPATH environment variable. You can also specify the classpath for a specific invocation of the
JVM via the java command’s -classpath option. (See Recipe 1-4 for an example.)
■
■ Note The CLASSPATH is certainly going to remain important for many Java applications into the future.
However, the new module system, introduced in Java 9, replaces the need to use the brittle CLASSPATH for
those applications that are built to take advantage of modularization. See Chapter 22 for more information on
Java Modularity.
When executing Java programs, the JVM finds and loads classes as needed using the following search
order:
1. The classes that are fundamental to the Java platform and are contained in the
Java installation directory.
2. Any packages or JAR files that are located within the extension directory of the
JDK.
3. Packages, classes, JAR files, and libraries that are loaded somewhere on the
specified class path.
You may need to access more than one directory or JAR file for an application. This could be the case
if your dependencies are located in more than one location. To do so, simply use the delimiter for your
operating system (; or :) as a separator between the locations specified by the CLASSPATH variable. Following
is an example of specifying multiple JAR files in the CLASSPATH environment variable on Unix and Linux
systems:
export CLASSPATH=/JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar
Alternatively, you can specify the class path via a command-line option:
javac –classpath /JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar
Chapter 1 ■ Getting Started with Java 9
11
When loading the resources for a Java application, the JVM loads all the classes and packages that are
specified in the first location, followed by the second, and so on. This is important because the order of
loading may make a difference in some instances.
■
■ Note JAR files are used to package applications and Java libraries into a distributable format. If you have
not packaged your application in that manner, you may simply specify the directory or directories in which your
.class files reside.
Sometimes you’ll want to include all JAR files within a specified directory. Do that by specifying the
wildcard character (*) after the directory containing the files. For example:
javac –classpath /JAVA_DEV/*:/JAVA_LIB/myjar.jar
Specifying a wildcard will tell the JVM that it should be loading JAR files only. It will not load class files
that are located in a directory specified with the wildcard character. You’ll need to specify a separate path
entry for the same directory if you also want the class files. For example:
javac –classpath /JAVA_DEV/*:/JAVA_DEV
Subdirectories within the class path will not be searched. In order to load files that are contained within
subdirectories, those subdirectories and/or files must be explicitly listed in the class path. However, Java
packages that are equivalent to the subdirectory structure will be loaded. Therefore, any Java classes that
reside within a Java package that is equivalent to the subdirectory structure will be loaded.
■
■ Note It is a good idea to organize your code; it is also good to organize where you place your code on
the computer. A good practice is to place all your Java projects within the same directory; it can become
your workspace. Place all the Java libraries that are contained in JAR files into the same directory for easier
management.
1-4. Organizing Code with Packages
Problem
Your application consists of a set of Java classes, interfaces, and other types. You want to organize these
source files to make them easier to maintain and avoid potential class-naming conflicts.
Solution
Create Java packages and place source files within them much like a filing system. Java packages can be used
to organize logical groups of source files within an application. Packages can help to organize code, reduce
naming conflicts among different classes and other Java type files, and provide access control. To create a
package, simply create a directory within the root of your application source folder and name it. Packages
are usually nested within each other and conform to a standard naming convention. For the purposes of this
Chapter 1 ■ Getting Started with Java 9
12
recipe, assume that the organization is named Juneau and that the organization makes widgets. To organize
all the code for the widget application, create a group of nested packages conforming to the following
directory structure:
/org/juneau
Any source files that are placed within a package must contain the package statement as the first line
in the source. The package statement lists the name of the package in which the source file is contained. For
instance, suppose that the main class for the widget application is named JuneauWidgets.java. To place
this class into a package named org.juneau, physically move the source file into a directory named juneau,
which resides within the org directory, which in turn resides within the root of the source folder for the
application. The directory structure should look like the following:
/org/juneau/JuneauWidgets.java
The source for JuneauWidgets.java is as follows:
package org.juneau;
/**
* The main class for the Juneau Widgets application.
* @author juneau
*/
public class JuneauWidgets {
    public static void main(String[] args){
        System.out println(Welcome to my app!);
    }
}
The first line in the source contains the package statement, which lists the name of the package that the
source file is located within. The entire package path is listed in the statement, and the names in the path are
separated by dots.
■
■ Note A package statement must be the first statement listed within the Java source. However, there may
be a comment or Javadoc comment written before the package statement. For more information on comments
or Javadoc, please see Recipe 1-12.
An application can consist of any number of packages. If the widget application contains a few classes
that represent widget objects, they could be placed within the org.juneau.widget package. The application
may have interfaces that can be used to interact with the widget objects. In this case, a package named org.
juneau.interfaces may also exist to contain any such interfaces.
How It Works
Java packages are useful for organizing source files, controlling access to different classes, and ensuring that
there are no naming conflicts. Packages are represented by a series of physical directories on a file system,
and they can contain any number of Java source files. Each source file must contain a package statement
Chapter 1 ■ Getting Started with Java 9
13
before any other statements in the file. This package statement lists the name of the package in which the
source file resides. In the solution to this recipe, the source included the following package statement:
package org.juneau;
This package statement indicates that the source file resides within a directory named juneau, and that
directory resides within another directory named org. Package-naming conventions can vary by company
or organization. However, it is important that words are in all lowercase so they do not conflict with any Java
class file names. Many companies or organizations will use the reverse of their domain name for package
naming. However, if a domain name includes hyphens, underscores should be used instead.
■
■ Note When a class resides within a Java package, it is no longer referenced by only the class name, but
instead the package name is prepended to the class name, which is known as the fully qualified name. For
instance, because the class that resides within the file JuneauWidgets.java is contained within the org.
juneau package, the class is referenced using org.juneau.JuneauWidgets, not simply JuneauWidgets.
An identically named class can reside within a different package (for instance, org.java9recipes.
JuneauWidgets).
Packages are very useful for establishing levels of security as well as organization. By default, different
classes that reside within the same package have access to each other. If a source file resides within a
different package than another file that it needs to use, an import statement must be declared at the top
of the source file (underneath the package statement) to import that other file for use; otherwise, the fully
qualified package.class name must be used within the code. Classes may be imported separately, as
demonstrated in the following import statement:
import org.juneau.JuneauWidgets;
However, it is often likely that all classes and type files that reside within a package need to be used.
A single import statement utilizing a wildcard character (*) can import all files within a named package as
follows:
import org.juneau.*;
Although it is possible to import all files, it is not recommended unless absolutely necessary. As a
matter of fact, it is considered a poor programming practice to include many import statements that use the
wildcard. Instead, classes and type files should be imported individually.
Organizing classes within packages can prove to be very helpful. Suppose that the widget application
that was described in the solution to this recipe includes different Java classes for each different widget
object. Each of the widget classes could be grouped into a single package named org.juneau.widgets.
Similarly, each of the widgets could extend some Java type or interface. All such interfaces could be
organized into a package named org.juneau.interfaces.
Any substantial Java application will include packages. Any Java library or Application Programming
Interface (API) that you use includes packages. When you import classes or types from those libraries and
APIs, you are really importing packages.
Chapter 1 ■ Getting Started with Java 9
14
1-5. Declaring Variables and Access Modifiers
Problem
You want to create some variables and manipulate data within your program. Furthermore, you wish to
make some of the variables available to only the current class, whereas others should be available to all
classes, or just the other classes within the current package.
Solution
Java implements eight primitive data types. There is also special support for the String class type. Listing 1-2
shows an example declaration of each. Draw from the example to declare the variables needed in your own
application.
Listing 1-2. Declarations for Primitive and String Types
package org.java9recipes.chapter01.recipe1_05;
public class DeclarationsExample {
    public static void main (String[] args) {
        boolean BooleanVal = true;  /* Default is false */
        char charval = 'G';     /* Unicode UTF-16 */
        charval = 'u0490';     /* Ukrainian letter Ghe(Ґ) */
        byte byteval;       /*  8 bits, -127 to 127 */
        short shortval;     /* 16 bits, -32,768 to 32,768 */
        int intval;         /* 32 bits, -2147483648 to 2147483647 */
        long longval;       /* 64 bits, -(2^64) to 2^64 - 1 */
        float   floatval = 10.123456F; /* 32-bit IEEE 754 */
        double doubleval = 10.12345678987654; /* 64-bit IEEE 754 */
        String message = Darken the corner where you are!;
        message = message.replace(Darken, Brighten);
    }
}
■
■ Note If you’re curious about the Ukrainian letter in Listing 1-2, it is the Cyrillic letter Ghe with upturn. You
can read about its history at: http://en.wikipedia.org/wiki/Ghe_with_upturn. You can find its code point
value in the chart at http://www.unicode.org/charts/PDF/U0400.pdf. And the URL http://www.unicode.
org/charts/ is a good place to start whenever you need to find the code point corresponding to a given
character.
Variables are subject to the concept of visibility. Those created in Listing 1-2 are visible from the main()
method after they have been created, and they are deallocated when the main() method ends. They have no
“life” beyond the main() method, and are not accessible from outside of main().
Chapter 1 ■ Getting Started with Java 9
15
Variables created at the class level are a different story. Such variables can be termed as class fields or
class members, as in fields or members of the class. Use of a member can be restricted to objects of the class
in which it is declared, to the package in which it is declared, or it can be accessible from any class in any
package. Listing 1-3 shows some of how to control visibility via the private and public keywords.
Listing 1-3. Visibility and the Concept of Fields
package org.java9recipes.chapter01.recipe1_05;
class TestClass {
    private long visibleOnlyInThisClass;
    double visibleFromEntirePackage;
    void setLong (long val) {
        visibleOnlyInThisClass = val;
    }
    long getLong () {
       return visibleOnlyInThisClass;
    }  
}
public class VisibilityExample {            
    public static void main(String[] args) {
        TestClass tc = new TestClass();  
        tc.setLong(32768);
        tc.visibleFromEntirePackage = 3.1415926535;
        System.out.println(tc.getLong());
        System.out.println(tc.visibleFromEntirePackage);
    }
}
Output:
32768
3.1415926535
Members are typically bound to an object of a class. Each object of a class contains an instance of each
member in the class. However, you can also define so-called static fields that occur just once, and with a
single value that is shared by all instances of the given class. Listing 1-4 illustrates the difference.
Listing 1-4. Static Fields
package org.java9recipes.chapter01.recipe1_05;
class StaticDemo {
    public static boolean oneValueForAllObjects = false;
}
public class StaticFieldsExample {
    public static void main (String[] args) {
        StaticDemo sd1 = new StaticDemo();
        StaticDemo sd2 = new StaticDemo();
        System.out.println(sd1.oneValueForAllObjects);
Chapter 1 ■ Getting Started with Java 9
16
        System.out.println(sd2.oneValueForAllObjects);
        sd1.oneValueForAllObjects = true;
        System.out.println(sd1.oneValueForAllObjects);
        System.out.println(sd2.oneValueForAllObjects);
    }
}
Listing 1-4 produces the following output:
false
false
true
true
The field oneValueForAllObjects was set to true only for the class instance named sd1. Yet it is true for
instance sd2 also. This is because of the keyword static used in declaring that field. Static fields occur one
time for all objects of their class.
How It Works
Listing 1-2 illustrates the basic format of a variable declaration:
type variable;
It’s common to initialize variables when declaring them, so you’ll often see:
type variable = initialValue;
Field declarations can be preceded by modifiers. For example:
public static variable = initialValue;
protected variable;
private variable;
It’s common to put the visibility modifier — public, protected, or private — first, but you are free to
list the modifiers in any order you like. Be aware that there are additional modifiers that you will encounter
and need to learn about as you get deeper into the language. By default, if no modifier has been specified,
the class or member is made package-private, meaning that only other classes within the package have
access to the member. If a class member is specified as protected, then it is also package-private, with the
exception that any subclass of its class in another package also has access.
The String type is special in Java. It’s really a class type, but syntactically you can treat it as a primitive
type. Java automatically creates a String object whenever you enclose a String of characters within double
quotes (...). You aren’t required to invoke a constructor, nor to specify the new keyword. Yet String is
a class, and there are methods in that class that are available to you. One such method is the replace()
method shown at the end of Listing 1-2.
Strings are composed of characters. Java’s char type is a two-byte construct for storing a single character
in Unicode-s UTF-16 encoding. You can generate literals of the char type in two ways:
• If a character is easy to type, then enclose it within single quotes (e.g.: 'G').
• Otherwise, specify the four-digit UTF-16 code point value prefaced by u
(e.g.: 'u0490').
Chapter 1 ■ Getting Started with Java 9
17
Some Unicode code points require five digits. These cannot be represented in a single char value.
See Chapter 12 if you need more information on Unicode and internationalization.
Avoid using any of the primitive types for monetary values. Especially avoid either of the floating-point
types for that purpose. Refer instead to Chapter 12 and its recipe on using the Java Money API to calculate
monetary amounts (Recipe 12-10). BigDecimal can also be useful anytime you need accurate, fixed-decimal
arithmetic.
If you are new to Java, you may be unfamiliar with the String[] array notation, as demonstrated in
the examples. Please see Chapter 7 for more information on arrays. It covers enumerations, arrays, and
also generic data types. Also in that chapter are examples showing how to write iterative code to work with
collections of values such as an array.
1-6. Compiling and Executing from the Command-Line or
Terminal Interpreter
Problem
You aren’t able to install an IDE, or prefer to use a standard text editor for development. Moreover, you want
to compile and execute your Java programs from the command line or terminal so that you have complete
control over the environment.
Solution
Compile your programs using the javac command. Then execute them via the java command.
Begin by making sure you have your JDK’s bin directory in your execution path. You might need to
execute a command such as one of the following.
Windows:
setx path %path%;C:Program FilesJavajdk1.9.0bin
OS X:
export PATH=/Library/Java/JavaVirtualMachines/jdk1.9.0.jdk/Contents/Home/bin
Then make sure your CLASSPATH environment variable includes the directory containing your Java code.
The following is an example of setting the environment variable under Windows:
set CLASSPATH=path-to-my-Java
Now change your current working directory to be the one corresponding to your project. Recipe 1-2
had you create a project named Java9Recipes. Change to that project’s directory on a Windows system as
follows:
cd path-to-projectJava9Recipes
Descend one level into the src subdirectory:
cd src
Chapter 1 ■ Getting Started with Java 9
18
From here, you can issue javac commands to compile any classes in your project. Prepend the
appropriate package name as part of your path leading to each source file to be compiled. Be sure to
include the .java extension after your file name. For example, issue the following command to compile the
HelloWorld class from Recipe 1-2.
Windows:
javac orgjava9recipeschapter01recipe1_02HelloWorld.java
OS X:
javac org/java9recipes/chapter01/recipe1_02/HelloWorld.java
Once the compilation is complete, you will have a .class file in the same directory as your .java file.
For example, if you perform a directory listing, you should see four files:
dir orgjava9recipeschapter01recipe1_02
HelloMessage.class
HelloWorld.class
HelloMessage.java
HelloWorld.java
Compilation produces two files. One is for HelloMessage, and the other is for the class named
HelloWorld implementing the main() method.
Execute the main() method by issuing the java command to invoke the Java Virtual Machine (JVM).
Pass the fully qualified class name as a parameter to the command. Qualify the class name by prepending
the package name, but this time use the same dot-notation as used in your source file. For example:
java org.java9recipes.chapter1.recipe1_02.HelloWorld
Do not specify .class at the end of the command. You are referencing HelloWorld now as a class name,
and not as a file name. You should see the same output as from Recipe 1-2.
■
■ Tip One must compile source code. Source code is kept in files with a .java suffix, so your operating
system’s file and directory-path notation is appropriate. One executes a class. A class is an abstract concept in
the language, so the language’s dot-notation becomes appropriate. Keep this distinction in mind to help yourself
remember when to use which notation.
How It Works
The first two solution steps are housekeeping steps. You must have the Java compiler and the virtual
machine in your execution path. It’s also necessary for any classes used by your program to be found
somewhere along what is termed the classpath. One way to specify the class path is through the CLASSPATH
environment variable. See Recipe 1-3 for more information on the classpath.
Chapter 1 ■ Getting Started with Java 9
19
■
■ Note The Java Modularity system added a couple of options to the javac compiler. Please see Chapter 22
for more information.
The command java with no c at the end is for executing compiled code. Pass as a parameter the
qualified name of the class containing your main method. The JVM will interpret and execute the byte-
code within that class, beginning from the main method. The JVM will search along the classpath for any
additionally required classes such as HelloMessage.
The compiler’s default behavior is to place each generated class file into the same directory as holds the
corresponding source file. You can override that behavior through the -d option. For example:
javac -d specify-different-location path-to-project
Java9Recipessrcorgjava9recipeschapter1recipe1_02HelloWorld.java
The -d option in this command designates a directory in our own environment as the target for holding
generated class files. The command also specifies the full path and file name of the source file. Thus, the
command can be executed with the same result regardless of the current working directory.
■
■ Tip Configure your system so that your command-line environment has the execution path and classpath
set correctly by default. The typical approach in Linux- or Unix-based operating systems is to put appropriate
commands into your .profile or .bash_profile files. Under Windows you can specify environment variable
defaults from the Control Panel window named System, by clicking the Advanced system settings link, and then
the Environment Variables button.
There may be times when you need to specify a custom class path for a specific execution of the JVM.
You can do that through the -cp parameter, as follows:
java -cp .;path-to-projectJava9Recipesbuildclassesorgjava9recipeschapter1
recipe1_02
org.java9recipes.chapter1.recipe1_02.HelloWorld
This execution will search first in the current working directory (the leading dot in the classpath), and
then under the specified package directory corresponding to where NetBeans would place the compiled
classes.
■
■ Note See Recipe 1-3 for more on configuring your classpath.
1-7. Developing Within the Interactive jShell
Problem
You wish to write Java code and have it interpreted immediately, so that you can test, prototype, and alter
your code quickly, without the need to wait for compilation or the ceremony of writing an entire Java class to
perform a trivial task.
Chapter 1 ■ Getting Started with Java 9
20
Solution
Make use of the interactive jShell, new in Java 9, by opening a command prompt or terminal, and executing
the jshell utility. The jshell is located in your JDK home bin directory, just like the java and javac utilities.
Assuming that the JDK/bin directory is in the CLASSPATH, the jShell can be invoked using as such:
jshell
|  Welcome to JShell -- Version 1.9.0
|  Type /help for help
-
Once the interpreter has been started, declarations can be defined for the lifetime of the jShell session,
expressions and statements can be typed and executed immediately, and so on. The jShell also allows Java
developers to write a shorthand version of the language by eliminating superfluous constructs such as
semicolons. Listing 1-5 demonstrates some of the basic functionality that is provided by the jShell. Keep in
mind that when you are using the interactive shell, if you at any time need assistance, you can type the /help
command.
Listing 1-5. Interactive jShell
- System.out.println(Hello World)
Hello World
- 1 + 1
|  Expression value is: 2
|    assigned to temporary variable $1 of type int
- System.out.println(Hello Java 9)
Hello Java 9
- // working with classes
- class Main {
     // Main method
     public static void main(String[] args) {
         System.out.println(Classes within jShell);
         int index = 0;
         while(index = 10){
             System.out.println(Looping:  + index);
             index++;
         }
     }
 }
|  Added class Main
- // List classes currently loaded in jShell
- /classes
|    class Main
- // Execute Class
- Main.main(null)
Classes within jShell
Looping: 0
Looping: 1
Chapter 1 ■ Getting Started with Java 9
21
Looping: 2
Looping: 3
Looping: 4
Looping: 5
Looping: 6
Looping: 7
Looping: 8
Looping: 9
Looping: 10
- // Reset the state of the jshell
- /r
|  Resetting state.
- /classes
- // Using imports
- import java.util.ArrayList
- import java.util.List
- ListString colors = new ArrayList();
|  Added variable colors of type ListString with initial value []
- colors.add(red)
|  Expression value is: true
|    assigned to temporary variable $4 of type boolean
- colors.add(orange)
|  Expression value is: true
|    assigned to temporary variable $5 of type boolean
- colors.add(yellow)
|  Expression value is: true
|    assigned to temporary variable $6 of type boolean
- colors
|  Variable colors of type ListString has value [red, orange, yellow]
- // List the current jShell session variables
- /v
|    ListString colors = [red, orange, yellow]
|    boolean $4 = true
|    boolean $5 = true
|    boolean $6 = true
- // List the commands that have been executed
- /list
   1 : import java.util.ArrayList;
   2 : import java.util.List;
   3 : ListString colors = new ArrayList();
   4 : colors.add(red)
   5 : colors.add(orange)
   6 : colors.add(yellow)
   7 : colors
Chapter 1 ■ Getting Started with Java 9
22
As mentioned previously, one of the boons to having an interactive shell is for prototyping code. In
many cases, developers wish to prototype classes and objects. Listing 1-5 demonstrates how to type the code
for a class into the jShell, along with some of the commands that can be useful while working with classes.
When prototyping, it can oftentimes be helpful to copy code from your favorite editor and paste it into the
jShell, then execute commands against it.
How It Works
The jShell provides a Read Evaluate Print Loop (REPL) environment for developers to type or paste in code
“snippets” and have them executed immediately. Much like the REPL environments or other languages such
as Groovy, Python, and JRuby, the jShell provides an excellent environment for prototyping code, and even
for executing stored scripts of Java code on the fly.
The jShell allows one to write abbreviated Java code, otherwise known as snippets. This can be beneficial
as it allows one to focus on the logic, rather than the syntax. One of the most used shortcuts is the ability to
leave semicolons off the end of a line. To facilitate rapid prototyping, variables can be declared outside of
classes, expressions and methods can be typed on the fly outside of classes and interfaces, and expressions
leave no side effects. Along with the ability to write code on the fly, the jShell provides a system that facilitates
the addition, modification, and removal of code fragments within an active session or instance.
An active session or instance of the jShell environment constitutes a single JShellState. An instance
of the JShellState includes all previously defined variables, methods, classes, import statements, and
so on, that have been made within that same jShell session. Once the jShell instance is terminated, the
JShellState is ended, and therefore all declarations are lost.
There are a number of helper commands that can be typed into the jShell to retrieve information
regarding the current JShellState. The /classes command lists all of the classes that have been typed
into the current JShellState. The /list command lists all of the statements, expressions, classes, methods,
imports, and so on, that have been typed into the current JShellState. The /list command provides a line
number next to each of the listings, which enables one to easily re-execute that line of code using typing
/ followed by the line number that you wish to re-execute. Therefore, if you wish to execute line number
2 again, you would type /2 to have that line executed again. Table 1-1 contains a complete listing of the
commands available within jShell.
Table 1-1. jShell Commands
Command Description
/l or /list Lists the sources typed into the current session.
/e or /edit [name or id of source] Opens JShell Edit Pad. Optionally type the name or id of the source
entry to edit.
/d or /drop [name/id of source] Deletes or drops the source referenced by name or id.
/s or /save [all|history] Saves sources that have been typed in the current session.
/o or /open Opens a file of source within the jShell.
/v or /vars Lists variables that have been declared in the current session along
with their current values.
/m or /methods Lists the methods that have been declared in the current session.
/c or /classes Lists the classes that have been declared in the current session.
/x or /exit Exits the current jShell session.
/r or /reset Resets the JShellState for the current session.
(continued)
Chapter 1 ■ Getting Started with Java 9
23
If you type the /e command, a scratch pad editor known as “JShell Edit Pad” will open containing the
sources that you’ve entered for the current JShellState, as shown in Figure 1-6. You can edit the sources
within this pad and then click the “Accept” button to have those sources evaluated within jShell.
Figure 1-6. JShell Edit Pad
Command Description
/f or /feedback [level] Initiates feedback- options include (off, concise, normal, verbose,
default, or ?).
/p or /prompt Toggles the display of the prompt within the shell.
/cp or /classpath [path] Adds the typed path to the current CLASSPATH.
/h or /history Lists the history of the active JShellState.
/setstart [file] Reads and sets the startup definition file.
/savestart [file] Saves the current session’s definitions to the designated startup file.
/! Re-executes the last code snippet.
/n Re-executes the nth code snippet.
/-n Re-executes the nth previous code snippet.
Table 1-1. (continued)
Chapter 1 ■ Getting Started with Java 9
24
Other useful features of the jShell are that you can bring up the previously typed command by pressing
the up arrow on your keyboard. The interactive shell also features tab-completion. If you begin typing a
statement and then press the Tab key, either the statement will be autocompleted for you or a list of options
for the characters currently typed will be displayed. It is also possible to set up a predefined list of imports so
that each time a jShell session is started, those imports will occur automatically.
The jShell provides an interactive environment that allows immediate feedback while typing code
snippets. This can be beneficial for prototyping or learning the language. Other languages, such as Groovy,
Python, and Scala, have similar REPL environments. Now that the jShell is available for Java, it opens the
door for a more interactive environment for classroom use and increased developer prototyping productivity.
■
■ Tip To learn more about the commands available within the jShell, simply type /help once the shell has
opened. The help feature displays an extensive listing of the features available in the jShell.
1-8. Converting to and from a String
Problem
You have a value stored within a primitive data type, and you want to represent that value as a human-
readable String. Or, you want to go in the other direction by converting a human-readable String into a
primitive data type.
Solution
Follow one of the patterns from Listing 1-6. The listing shows conversion from a String to a double-precision
floating-point value, and shows two methods for getting back to a String again.
Listing 1-6. General Pattern for String Conversions
package org.java9recipes.chapter01.recipe1_08;
public class StringConversion {
    public static void main (String[] args) {
        double pi;
        String strval;
        pi = Double.parseDouble(3.14);
        System.out.println(strval = String.valueOf(pi));
        System.out.println(Double.toString(pi));
    }
}
How It Works
The solution illustrates some conversion patterns that work for all the primitive types. First, there is the
conversion of a floating-point number from its human-readable representation into the IEEE 754 format
used by the Java language for floating-point arithmetic:
pi = Double.parseDouble(3.14);
Chapter 1 ■ Getting Started with Java 9
25
Notice the pattern. You can replace Double with Float, or by Long, or by whatever other type is your
target data type. Each primitive type has a corresponding wrapper class by the same name but with the
initial letter uppercase. The primitive type here is double, and the corresponding wrapper is Double. The
wrapper classes implement helper methods such as Double.parseDouble(), Long.parseLong(), Boolean.
parseBoolean(), and so forth. These parse methods convert human-readable representations into values of
the respective types.
Going the other way, it is often easiest to invoke String.valueOf(). The String class implements this
method, and it is overloaded for each of the primitive data types. Alternatively, the wrapper classes also
implement toString() methods that you can invoke to convert values of the underlying type into their
human-readable forms. It’s your own preference as to which approach to take.
Conversions targeting the numeric types require some exception handling to be practical. You generally
need to gracefully accommodate a case in which a character-string value is expected to be a valid numeric
representation, but it’s not. Chapter 9 covers exception handling in detail, and the upcoming Recipe 1-10
provides a simple example to get you started.
■
■ Caution Literals for the Boolean type are true and false. They are case-sensitive. Any value
other than these two is silently interpreted as false when converting from a String using the Boolean
parseBoolean() conversion method.
1-9. Passing Arguments via Command-Line Execution
Problem
You want to pass values into a Java application that is being invoked via the command line via the java
utility.
Solution
Run the application using the java utility, and specify the arguments that you want to pass into it after the
application name. If you’re passing more than one argument, each should be separated by a space. For
example, suppose you want to pass the arguments to the class created in Listing 1-7.
Listing 1-7. Example of Accessing Command-Line Arguments
package org.java9recipes.chapter01.recipe1_09;
public class PassingArguments {
    public static void main(String[] args){
        if(args.length  0){
            System.out.println(Arguments that were passed to the program: );
            for (String arg:args){
                System.out.println(arg);
            }
        } else {
            System.out.println(No arguments passed to the program.);
        }
    }
}
Chapter 1 ■ Getting Started with Java 9
26
First, make sure to compile the program so that you have a .class file to execute. You can do that from
within NetBeans by right-clicking the file and choosing the “Compile File” option from the context menu, or
via the javac utility at the command line or terminal.
Next, open a Command Prompt or terminal window and traverse into the buildclasses directory for
your project. (See Recipe 1-6 for an extensive discussion of executing from the command line). For example:
cd path-to-projectJava9Recipesbuildclasses
Now issue a java command to execute the class, and type some arguments on the command line
following the class name. The following example passes two arguments:
java org.java9recipes.chapter01.recipe1_09.PassingArguments Upper Peninsula
You should see the following output:
Arguments that were passed to the program:
Upper
Penninsula
Spaces separate arguments. Enclose Strings in double quotes when you want to pass an argument
containing spaces or other special characters. For example:
java org.java9recipes.chapter01.recipe1_09.PassingArguments Upper Peninsula
The output now shows just one argument:
Arguments that were passed to the program:
Upper Penninsula
The double quotes translate the String Upper Peninsula into a single argument.
How It Works
All Java classes that are executable from the command line or terminal contain a main() method. If you look
at the signature for the main() method, you can see that it accepts a String[] argument. In other words,
you can pass an array of String objects into the main() method. Command-line interpreters such as the
Windows Command Prompt and the various Linux and Unix shells build an array of Strings out of your
command-line arguments, and pass that array to the main() method on your behalf.
The main() method in the example displays each argument that is passed. First, the length of the array
named args is tested to see whether it is greater than zero. If it is, the method will loop through each of the
arguments in the array by executing a for loop, displaying each argument along the way. If there are no
arguments passed, the length of the args array will be zero, and a message indicating such will be printed.
Otherwise, you see a different message followed by a list of arguments.
Command-line interpreters recognize spaces and sometimes other characters as delimiters. It’s
generally safe to pass numeric values as arguments delimited by spaces without bothering to enclose each
value within quotes. However, you should get into the habit of enclosing character-string arguments in
double quotes, as shown in the final solution example. Do that to eliminate any ambiguity over where each
argument begins and ends.
Chapter 1 ■ Getting Started with Java 9
27
■
■ Note All arguments are seen by Java as character Strings. If you pass numeric values as parameters, they
enter Java as character Strings in human-readable form. You can convert them into their appropriate numeric
types using the conversion methods shown in Recipe 1-8.
1-10. Executing a Script via the jShell
Problem
You wish to write a prototype or script and execute it via the jShell utility from the command line or terminal.
Solution
While the jShell is not intended to provide a new language syntax for Java development, it is possible to
save source snippets for execution within the jShell into a file, and then pass the file to the jShell utility for
execution. In this solution, we’ll save a simple snippet into a file named myScript.java, and execute it with
the jShell utility.
To get started, save the following source code into a file named myScript.java, and save it to your file
system.
System.out.println(Hello from jShell)
/x
Execute the script using the following syntax:
jShell path-to-file/myScript.java
Output:
Hello from jShell
How It Works
Sometimes it can be beneficial to use a text editor or the JShell Edit Pad (see Recipe 1-7) to save sources that
can be executed within the jShell environment. This increases the ability to rapidly prototype code, and it
also facilitates the ability to develop scripts that can be executed time and time again. This can be useful for
development of scheduled tasks or administrative tasks that can be executed by the JVM. As such, sources
for the jShell can be stored into a file containing the extension of your choice, and then the file can be passed
to the jShell for execution.
In the solution, a simple String is printed as output, and then the jShell environment is exited. Notice
that the /x command is placed on a separate line after the sources within the file. The /x command tells the
jShell environment to exit upon completion. If exiting upon completion, any variables, method, classes,
and so on, that are defined within the file are lost once the sources have run to completion and the jShell
environment is closed.
It is not recommended to write applications using the jShell environment for execution. In fact, GUI
applications are out of scope for the jShell, and debuggers are also not supported. The environment is clearly
intended for educational and prototyping purposes. However, some may find it handy to save snippets of
code for execution via the jShell at a later time.
Chapter 1 ■ Getting Started with Java 9
28
1-11. Accepting Input from the Keyboard
Problem
You are interested in writing a command-line or terminal application that will accept user input from the
keyboard.
Solution
Make use of the java.io.BufferedReader and java.io.InputStreamReader classes to read keyboard entry
and store it into local variables. Listing 1-8 shows a program that will keep prompting for input until you
enter some characters that represent a valid value of type long.
Listing 1-8. Keyboard Input and Exception Handling
package org.java9recipes.chapter01.recipe1_11;
import java.io.*;
public class AcceptingInput {
    public static void main(String[] args){
        BufferedReader readIn = new BufferedReader(
                new InputStreamReader(System.in)
        );
        String numberAsString = ;
        long numberAsLong = 0;
        boolean numberIsValid = false;
        do {
            /* Ask the user for a number. */
            System.out.println(Please enter a number: );
            try {
                numberAsString = readIn.readLine();
                System.out.println(You entered  + numberAsString);
            } catch (IOException ex){
                System.out.println(ex);
            }
            /* Convert the number into binary form. */
            try {
                numberAsLong = Long.parseLong(numberAsString);
                numberIsValid = true;
            } catch (NumberFormatException nfe) {
                System.out.println (Not a number!);
            }
        } while (numberIsValid == false);  
    }
}
Chapter 1 ■ Getting Started with Java 9
29
Following is an example run of this program:
Please enter a number:
No
You entered No
Not a number!
Please enter a number:
Yes
You entered Yes
Not a number!
Please enter a number:
42
You entered 42
BUILD SUCCESSFUL (total time: 11 seconds)
The first two inputs did not represent valid values in the long data type. The third value was valid, and
the run ended.
How It Works
Quite often our applications need to accept user input of some kind. Granted, most applications are not
used from the command line or terminal nowadays, but having the ability to create an application that
reads input from the command line or terminal helps to lay a good foundation, and may be useful in some
applications or scripts. Terminal input can also be useful in developing administrative applications that you
or a system administrator may use.
Two helper classes were used in the solution to this recipe. They are java.io.BufferedReader and
java.io.InputStreamReader. The early portion of the code that’s using those classes is especially important
to understand:
BufferedReader readIn = new BufferedReader(
        new InputStreamReader(System.in)
);
The innermost object in this statement is System.in. It represents the keyboard. You do not need to
declare System.in. Java’s runtime environment creates the object for you. It is simply available to be used.
System.in provides access to raw bytes of data from the input device, which is the keyboard in our
example. It is the job of the InputStreamReader class to take those bytes and convert them into characters
in your current character set. System.in is passed to the InputStreamReader() constructor to create an
InputStreamReader object.
InputStreamReader knows about characters, but not about lines. It is the BufferedReader class’s
job to detect line breaks in the input stream, and to enable you to conveniently read a line at a time.
BufferedReader also aids efficiency by allowing physical reads from the input device to be done in different-
size chunks than by which your application consumes the data. This aspect can make a difference when the
input stream is a large file rather than the keyboard.
Following is how the program in Listing 1-8 makes use of an instance (named readIn) of the
BufferedReader class to read a line of input from the keyboard:
numberAsString = readIn.readLine();
Chapter 1 ■ Getting Started with Java 9
30
Executing this statement triggers the following sequence:
1. System.in returns a sequence of bytes.
2. InputStreamReader converts those bytes into characters.
3. BufferedReader breaks the character stream into lines of input.
4. readLine() returns one line of input to the application.
I/O calls must be wrapped in try-catch blocks. These blocks are used to catch any exceptions that may
occur. The try part in the example will fail in the event a conversion is unsuccessful. A failure prevents the
numberIsValid flag from being set to true, which causes the do loop to make another iteration so that the
user can try again at entering a valid value. To learn more about catching exceptions, please see Chapter 9.
The following statement at the top of Listing 1-8 deserves some mention:
import java.io.*;
This statement makes available the classes and methods defined in the java.io package. These include
InputStreamReader and BufferedReader. Also included is the IOException class used in the first try-catch
block.
1-12. Documenting Your Code
Problem
You want to document some of your Java classes to assist in future maintenance.
Solution
Use Javadoc to place comments before any class, method, or field that you want to document. To begin such
a comment, write the characters /**. Then begin each subsequent line with an asterisk (*). Lastly, close the
comment with the characters */ on a line by themselves at the end. Listing 1-9 shows a method commented
with Javadoc.
Listing 1-9. Comments Made in Javadoc Form
package org.java9recipes.chapter01.recipe1_12;
import java.math.BigInteger;
public class JavadocExample {
    /**
     * Accepts an unlimited number of values and
     * returns the sum.
     *
     * @param nums Must be an array of BigInteger values.
     * @return Sum of all numbers in the array.
     */
Chapter 1 ■ Getting Started with Java 9
31
     public static BigInteger addNumbers(BigInteger[] nums) {
         BigInteger result = new BigInteger(0);
         for (BigInteger num:nums){
             result = result.add(num);
         }
         return result;
     }
    /**
     * Test the addNumbers method.
     * @param args not used
     */
     public static void main (String[] args) {
         BigInteger[] someValues = {BigInteger.TEN, BigInteger.ONE};
         System.out.println(addNumbers(someValues));
     }
}
Comments can be added to the beginning of classes and fields in the same way. The comments
are helpful to you and other programmers maintaining the code, and their specific format enables easy
generation of an HTML reference to your code.
Generate the HTML reference by invoking the tool named Javadoc. This is a command-line tool
that parses a named Java source file and formulates HTML documentation based upon the defined class
elements and Javadoc comments. For example:
javadoc JavadocExample.java
This command will produce several HTML files containing the documentation for the class, methods,
and fields. If no Javadoc comments exist within the source, some default documentation will still be
produced. To view the documentation, load the following file into your browser:
index.html
The file will be in the same directory as the class or package that you are documenting. There will also
be an index-all.html file giving a strict alphabetical listing of documented entities.
Keep in mind that the same rules apply when using the Javadoc tool as when using javac. You must
reside within the same directory as the source file, or prepend the name of the file with the path to where the
file is located.
How It Works
Generating documentation for applications from scratch can be quite tedious. Maintaining documentation
can be even more troublesome. The JDK comes packaged with an extensive system for documentation
known as Javadoc. Placing some special comments throughout your code source and running a simple
command-line tool makes it easy to generate useful documentation and keep it current. Moreover, even
if some of the classes, methods, or fields in an application are not commented specifically for the Javadoc
utility, default documentation will still be produced for such elements.
Chapter 1 ■ Getting Started with Java 9
32
Formatting the Documentation
To create a Javadoc comment, begin with the characters /**. Although optional since Java 1.4, a common
practice is to include an asterisk as the first character of every subsequent line within the comment. Another
good practice is to indent the comment so that it aligns with the code that is being documented. Lastly, close
the comment with the characters */.
Javadoc comments should begin with a short description of the class or method. Fields are rarely
commented using Javadoc, unless they are declared public static final (constants), in which case it is a
good idea to supply a comment. A comment can be several lines in length, and can even contain more than
one paragraph. If you want to break comments into paragraphs, then separate those paragraphs using the
p tag. Comments can include several tags that indicate various details regarding the method or class that is
being commented. Javadoc tags begin with an ampersand (@), and some of the common tags are as follows:
@param: Name and description of a parameter
@return: What is returned from the method
@see: Reference to another piece of code
You may also include inline links within Javadoc to reference URLs. To include an inline link, use the
tag {@link My Link}, where link is the actual URL that you want to point at and My Link is the text that you
want to have appear. There are also many other tags that can be used within Javadoc comments, including
{@literal}, {@code}, {@value org}, and many others. For a complete listing, see the Javadoc reference on
the OTN website.
Executing the Tool
The Javadoc tool can also be run against entire packages or source. Simply pass a package name to the
Javadoc tool rather than individual source file names. For instance, if an application includes a package
named org.juneau.beans, all source files within that package can be documented by running the tool as
follows:
javadoc org.juneau.beans
To generate Javadoc for more than one package at a time, separate the package names with spaces as
follows:
javadoc org.juneau.beans org.juneau.entity
Another option is to specify the path to the source files using the –sourcepath flag. For example:
javadoc –sourcepath /java/src
By default, the Javadoc tool will generate HTML and place it into the same package as the code being
documented. That result can become a cluttered nightmare if you like to have source files separate from
documentation. You can instead set up a destination for the generated documentation by passing the –d flag
to the Javadoc tool.
Chapter 1 ■ Getting Started with Java 9
33
1-13. Reading Environment Variables
Problem
The application you are developing needs to make use of some environment variables. You want to read the
values that have been set from the operating-system level.
Solution
Make use of the Java System class to retrieve any environment variable values. The System class has
a method called getenv(), which accepts a String argument corresponding to the name of a system
environment variable. The method will then return the value of the given variable. If no matching
environment variable exists, a NULL value will be returned. Listing 1-10 provides an example. The class
ReadOneEnvVariable accepts an environment variable name as a parameter, and displays the variable’s
value that has been set at the operating-system level.
Listing 1-10. Reading an Environment Variable’s Value
package org.java9recipes.chapter1.recipe1_13;
public class ReadOneEnvVariable {
    public static void main(String[] args) {
        if (args.length  0) {
            String value = System.getenv(args[0]);
            if (value != null) {
                System.out.println(args[0].toUpperCase() +  =  + value);
            } else {
                System.out.println(No such environment variable exists);
            }
        } else {
            System.out.println(No arguments passed);
        }
    }
}
If you are interested in retrieving the entire list of environment variables that is defined on a system, do
not pass any arguments to the System.getenv() method. You’ll receive back an object of type Map having all
the values. You can iterate through them as shown in Listing 1-11.
Listing 1-11. Iterating Through a Map of Environment Variables
package org.java9recipes.chapter1.recipe1_13;
import java.util.Map;
public class ReadAllEnvVariables {
    public static void main(String[] args){
        if(args.length  0){
            String value = System.getenv(args[0]);
        if (value != null) {
            System.out.println(args[0].toUpperCase() +  =  + value);
Chapter 1 ■ Getting Started with Java 9
34
        } else {
            System.out.println(No such environment variable exists);
        }
        } else {
            MapString, String vars = System.getenv();
            for(String var : vars.keySet()){
                System.out.println(var +  =  + vars.get(var));
            }
        }
    }
}
How It Works
The System class contains many different utilities that can aid in application development. One of those is
the getenv() method, which will return a value for a given system environment variable.
You can also return the values from all variables, in which case those values are stored in a map. A map
is a collection of name/value pairs. Chapter 7 provides additional information about maps, including a
recipe showing in detail how to iterate over them.
The method invoked to obtain environment variable values in Listings 1-10 and 1-11 is the same. It’s
been overloaded to handle both cases shown in the solution. Pass the name of a variable as a String if you
want to obtain just that variable’s value. Pass no argument at all to get back the names and values of all
variables that are currently set.
Summary
This chapter included recipes that allow you to get started working with Java quickly. It covered installation
of the JDK, to installation and use of the NetBeans IDE. The chapter also covered basics such as declaring
variables, compiling code, and documentation. The rest of this book dives deeper into each of the different
areas of the Java language, covering a variety of topics from beginner to expert. Refer to this chapter for
configuration specifics as you work through the examples in the rest of the book.
35
© Josh Juneau 2017
J. Juneau, Java 9 Recipes, DOI 10.1007/978-1-4842-1976-8_2
CHAPTER 2
Java 9 Enhancements
Each release of the JDK brings forth new enhancements and capability to the Java platform. Each release
also carries with it backward compatibility with previous releases. This book includes a number of recipes
covering the new features for Java 9, and this chapter showcases a few of the top enhancements to whet your
appetite. By no means is this chapter a complete listing of all Java 9 enhancements. Rather, it is a jump start
to get you going on some of the hot new features of Java 9.
2-1. Avoiding Redundancy in Interface Code
Problem
You would like to implement two or more default methods within an interface that will contain very similar
code. Rather than copying code into each of the different default methods and maintaining each default
method separately, you’d like to encapsulate the similar code into its own method for reuse.
Solution
Make use of a private method in an interface to alleviate this issue. Java 9 provides the ability to include
private methods within an interface. A private method is only available within that interface, and it cannot
be used by any class that implements the interface. However, each default method implementation that is
part of the interface can make use of the private method.
The following interface includes two default methods and one private method. The private method
encapsulates functionality that can then be used in each of the default method implementations.
public interface Pool {
    /**
     * Calculate volume (gal) for a fixed depth square or rectangular pool.
     */
    
public default double squareOrRectConstantDepth(double length, double width,
double depth){
        return volumeCalc(length, width, depth);
    }
    /**
     * Calculate volume (gal) for a variable depth square or rectangular pool.
     */
Chapter 2 ■ Java 9 Enhancements
36
    public default double squareOrRectVariableDepth(double length, double width,
                                                    double shallowDepth, double middleDepth,
                                                    double deepDepth){
        double avgDepth = (shallowDepth + middleDepth + deepDepth) / 3;
        return volumeCalc(length, width, avgDepth);
    }
    /**
     * Standard square or rectangular volume calculation.
     */
    private double volumeCalc(double length, double width, double depth){
        return length * width * depth * 7.5;
    }
}
How It Works
Prior to Java 8, it was not possible to include code implementation within a Java interface. An interface
is a reference type in Java, similar to a class. However, its original intent only allowed abstract methods,
constants, static methods, and nested types. Therefore, classes that implemented an interface must
implement each of the abstract methods. In Java 8, that restriction was lifted, and it became possible
to include method implementations in the form of default methods. A default method can contain an
implementation in the interface, or its implementation could be overridden by an implementing class.
Hence, the name default method, meaning that the default method implementation resides in the interface
if one is not provided by the implementation class. Private methods were not allowed in interfaces.
Situations have arisen by which multiple default methods within an interface may contain similar
code. This code can now be encapsulated within a private method implementation within the interface. The
private method implementation cannot be used outside of the interface. It can only be used by any default
methods contained within the same interface. In the solution to this recipe, the volumeCalc() method
returns the calculated volume of a square or rectangular swimming pool using a standard formula. Each of
the default methods within the interface are able to utilize the volumeCalc() method to find the volume.
However, the volumeCalc() method will not be available for use outside of the interface.
This seems to be a controversial topic, as interfaces were originally intended for field and method
declarations only, but it can also be argued that copying the same code throughout a number of default
method implementations would be a bad practice. Take it as you will, this feature makes it easier to reuse
code within an interface, thereby reducing the chance for errors and making maintenance much easier.
2-2. Creating Modules for Simplifying and Code Reuse
Problem
You are writing a utility library or a Java application, and you do not wish to rely upon the classpath to
manage dependencies with other libraries. Furthermore, you wish to package your library such that it can
easily be integrated into other projects.
Solution
Develop your library or application as a module. Creation of modules is quite easy. However, modules can
themselves become quite complex. This example will cover the creation of a very simple module that does
not depend upon any other modules. No other modules will depend upon the module either. Begin by
Chapter 2 ■ Java 9 Enhancements
37
creating a new directory somewhere on your file system…in this case name it “recipe2-2.” Create a new
folder named src within it, and then create a file named module-info.java, which is the module descriptor,
within the src folder. In this file, list the module name as follows:
module org.acme {}
Next, create a folder named org.acme.wordcount within the src directory that was created previously
(Figure 2-1). Next, create a folder named org within the org.acme.wordcount folder. Subsequently, create an
acme folder within the org folder, followed by a wordcount folder within the acme folder.
Figure 2-1. Module folder hierarchy
Now, create the bulk of the module by adding a new file named WordCount.java inside of the wordcount
folder. Place the following code within the WordCount.java file:
package org.acme.wordcount;
public class WordCount {
    public static void main(String[] args) {
        int counter = 0;
        if (args.length  0){
            for(String arg:args){
                System.out.println(Position  + counter + :  + arg.length());
                counter++;
            }
        }
    }    
}
Make use of the javac utility to compile the module by using the command line or terminal and
traversing inside of the src directory you created earlier. Issue the javac command, specifying the -d flag
to list the folder into which the compiled code will be placed. List each of the source files to be compiled,
including the module-info.java descriptor, separating each with a space. The following command compiles
the sources that were developed in and places the result into a directory named mods/org.acme.wordcount.
javac -d src/mods/org.acme.wordcount src/module-info.java src/org.acme.wordcount/org/acme/
wordcount/WordCount.java
Chapter 2 ■ Java 9 Enhancements
38
Now that the code has been compiled, it is time to execute the module. Use the java executable,
specifying the --module-path option, which is new in Java 9, to indicate the path of the module sources. The
-m option is used to specify the Main class of the module. Traverse inside of the src directory and issue the
following:
java --module-path mods -m org.acme.wordcount/org.acme.wordcount.WordCount testing one two
three
This example passes the words “testing,” “one,” “two,” “three” to the module to be counted. The output
should look as follows:
Position 0: 7
Position 1: 3
Position 2: 3
Position 3: 5
How It Works
Project Jigsaw brought modules into fruition for the Java platform, finally introducing a means to do away with
the classpath of the old, and make use of a newer, more pluggable architecture. The Java 9 module system
allows one to package self contained modules of code and make them versatile such that a module can be
made to depend upon other modules, or on the other hand, other modules can be made to depend upon it.
This modular dependency takes place of the old classpath system, although the classpath is still available for
use to accommodate backward compatibility and also for cases where modularity makes little sense.
Creation of a module consists of a module-info.java descriptor file. This file is used to indicate the
package containing the module, as well as the dependency contracts that the module shares with other
modules. Please see Chapter 22 for more details on the descriptor file.
The self-contained application in this recipe resides within the org.acme.wordcount.WordCount.java
file, and it can be compiled with javac, and executed with the java executable, as one would imagine. These
two utilities have new options available to support modularity, and the recipe demonstrates the use of these
new options for compiling and executing the module. For more details regarding module compilation and
execution, see Recipe 22-2.
2-3. Easily Retrieving Information on OS Processes
Problem
You would like the ability to find information regarding operating system processes.
Solution
Make use of the updated Process API in Java 9. The new ProcessHandle interface allows one to easily obtain
information regarding operating system processes. In the following code, all operating system processes are
listed and printed to the command line.
public static void listProcesses(){
    ProcessHandle.allProcesses()
            .forEach(System.out::println);
}
Chapter 2 ■ Java 9 Enhancements
39
However, this is not very helpful, as it simply lists the process number of each operating system
process…which is not very useful. To obtain more detail on the process, we need to obtain the
ProcessHandle and call upon its helper methods, which is quite easy to do. The following code will print
much more information regarding each process, as it prints the ProcessHandle.Info itself.
public static void detailListProcesses(){
    ProcessHandle.allProcesses()
            .forEach(h-System.out.println(formattedProcess(h)));
}
public static String formattedProcess(ProcessHandle handle){
        long pid = handle.getPid();
        boolean alive = handle.isAlive();
        OptionalDuration cpuDuration = handle.info().totalCpuDuration();
        OptionalString handleName = handle.info().command();
        return pid +   + alive +   + handleName + :+ cpuDuration;
     }
Sample output may look as follows:
17584 true Optional[/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/
java]:Optional[PT0.250501S]
17581 true Optional[/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/
java]:Optional.empty
17576 true Optional.empty:Optional.empty
17575 true Optional.empty:Optional.empty
17574 true Optional.empty:Optional.empty
17364 true Optional[/System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.
framework/Versions/A/Support/mdworker]:Optional.empty
17247 true Optional[/Applications/Google Chrome.app/Contents/Versions/56.0.2924.87/Google
Chrome Helper.app/Contents/MacOS/Google Chrome Helper]:Optional.empty
If you wish to retrieve information pertaining to the user that is running the process, that is easy to do
as well.
public static void detailListProcessUsers(){
    ProcessHandle.allProcesses()
            .forEach(h-System.out.println(listOsUser(h)));
}
public static String listOsUser(ProcessHandle handle){
    ProcessHandle.Info procInfo = handle.info();
    return handle.getPid() + :  +procInfo.user();
}
Sample output using this technique may look as follows:
17584: Optional[Juneau]
17581: Optional[Juneau]
17576: Optional[_postfix]
17575: Optional[_postfix]
17574: Optional[root]
Chapter 2 ■ Java 9 Enhancements
40
How It Works
Prior to the release of Java 9, it was cumbersome to obtain information regarding operating system
processes. We had to obtain process IDs using the ManagementFactory.getRuntimeMXBean() method and
then parse the String that was returned. The ProcessHandle interface is introduced in Java 9, making the
retrieval of operating system process information a first class citizen of the JDK. Table 2-1 shows the methods
that can be called upon within ProcessInfo in order to retrieve the desired information.
Table 2-1. ProcessHandle Interface
Method Description
allProcesses() Snapshot of all processes that are visible to the current process.
children() Snapshot of the children of the current process.
compareTo(ProcessHandle) Compare one ProcessHandle to another.
current() Returns the ProcessHandle for the current process.
descendants() Snapshot of all descendants of the current process.
destroy() Requests the process to be killed. Returns a boolean to indicate result.
destroyForcibly() Requests the process to be killed forcibly. Returns a boolean to indicate
result.
equals(Object) Returns a true if the object passed in is not null, and represents the same
system process, otherwise returns a false.
getPid() Returns the process ID for the process.
hashCode() Returns hash code value for the process.
info() Returns ProcessHandle.Info, which is a snapshot of information about
the current process.
isAlive() Returns a boolean to indicate whether the process is alive.
of(long) Returns OptionalProcessHandle for an existing native process.
onExit() Returns CompletableFutureProcessHandle for the termination of the
process. The CompletableFuture can then be called upon to determine
status.
parent() Returns OptionalProcessHandle for the parent of the current process.
supportsNormalTermination() Returns true if implementation of destroy() will terminate the process
normally.
2-4. Handling Errors with Ease
Problem
You’d like to easily manage the closing of effectively final variables.
Chapter 2 ■ Java 9 Enhancements
41
Solution
The try-with-resources construct was introduced in Java 7, and it allows for easy management of resources.
In Java 9, it became even easier as there is no need to effectively create a new variable for the sake of the
construct. In the following code, the writeFile() method takes a BufferedWriter as an argument, and
since it is passed into the method and ready to use, it is effectively final. This means that it can simply be
listed in the try-with-resources, rather than creating a new variable.
public static void main(String[] args) {
    try {
        writeFile(new BufferedWriter(
                new FileWriter(Easy TryWithResources)),
                This is easy in Java 9);
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
public static void writeFile(BufferedWriter writer, String text) {
    try (writer) {
        writer.write(text);
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
Prior to Java 9, the writeFile would have looked as follows:
public static void writeFile(BufferedWriter writer, String text) {
   try (BufferedWriter w = writer) {
        w.write(text);
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
This code will create a new file named “Easy TryWithResources” and it will put the text “This is easy in
Java 9” into the file.
How It Works
The try-with-resources construct has become even easier with Java 9. The try-with-resources construct was
introduced in Java 8, which allows one to handle the opening and closing of resources very easily. If we have
a resource, such as a database Connection or a BufferedStream, it is a good idea to manage wisely. In other
words, open the resource, then use it accordingly, and finally close the resource when finished to ensure that
there are no resource leaks. The try-with-resources construct allows one to open a resource within the try
block and have it automatically cleaned up once the block completes.
In the solution, the original way to handle resources is shown, followed by the new way in Java 9. It is
now possible to simply begin making use of a resource within a try-with-resources construct if it is passed
into a method as an argument or if it is a final field. This means that is no longer necessary to create a
placeholder variable for the purposes of utilization within the try-with-resources. While this is not a major
language change, it will certainly make handling resources a bit easier, and it certainly makes the try-with-
resources block even easier to understand.
Chapter 2 ■ Java 9 Enhancements
42
2-5. Filtering Data Before and After a Condition with
Streams
Problem
You wish to utilize streams for effective manipulation of your collections. While doing so, you wish to filter
those streams before and/or after a specified condition occurs. In the end, you want to retrieve all data
within the collection before a given predicate condition is met. You also wish to retrieve all data within the
collection that is placed after a given predicate condition is met.
Solution
Utilize the new Java 9 takeWhile() and dropWhile() constructs with your stream. Suppose we have the following
collection of data, and we wish to retrieve all of the elements prior to the element containing the word “Java.”
ListString myLangs = Arrays.asList(Jython is great,Groovy is awesome,
Scala is functional, JRuby is productive,Java is streamlined,,Kotlin is
interesting);
To retrieve all elements prior to the element containing the String “Java”
, we could use the takeWhile()
construct, as follows:
Stream.of(Jython is great,Groovy is awesome,Scala is functional,
                JRuby is productive,Java is streamlined,,Kotlin is interesting)
                .takeWhile(s - !s.contains(Java))
                .forEach(System.out::println);
Let’s suppose that we wish to retrieve all elements that occur after the element containing the String
“Java”
. We could use the dropWhile() construct, as follows:
Stream.of(Jython is great,Groovy is awesome,Scala is functional,
                JRuby is productive,Java is streamlined,,Kotlin is interesting)
                .dropWhile(s - !s.contains(Java))
                .forEach(System.out::println);
How It Works
Streams changed the way that we develop code and handle collections of data in Java. The original set of
filters that were available for use with streams was fairly generous. However, in Java 8, even more options
have been added, making it even easier to refine data with streams. The takeWhile() and dropWhile()
constructs allow streams to be parsed, returning a new stream that contains all elements before the first one
that fails the specified predicate condition, or returning a new stream containing all elements including and
after the first element that fails a specified predicate, respectively.
In the solution to this recipe, the list of Strings is parsed, printing each of the elements to the
command line for the first pass. The takeWhile() construct is then applied to the same stream of Strings
and the elements from the stream before the element that fails the specified condition will be printed to
the command line. The takeWhile() accepts a predicate condition, which it then applies to each of the
elements in the stream, and then only those elements that are iterated before the predicate condition is not
matched will be returned. All elements that reside in the stream at and after the position where the condition
is not met will not be returned.
Chapter 2 ■ Java 9 Enhancements
43
The opposite result occurs when using the dropWhile() construct. In the solution, all stream elements
will be ignored up until the first element upon which the specified condition is no longer met will be
returned. Each subsequent element in the stream will also be returned.
The takeWhile and dropWhile constructs are very similar to the filter, with the exception that only one
failed condition will cause the remaining elements to be ignored or returned, respectively.
2-6. Developing a Concise HTTP Client
Problem
You wish to develop an HTTP client within a Java application.
Solution
Make use of the updated HTTP/2 client for Java 9. In the following example, the Apress website is parsed and
returned via HTTP client code. In the following example, the Apress web page for US is returned as a String.
HttpResponse r1;
try {
    r1 = HttpRequest.create(new URI(http://www.apress.com/us/))
            .GET()
            .response();
    int responseCode = r1.statusCode();
    if(responseCode == 200){
        System.out.println(r1.body(asString()));
    }
} catch (URISyntaxException|IOException|InterruptedException ex) {
    // Log error
}
The output will look something like the following (abbreviated for brevity):
!DOCTYPE html
!--[if lt IE 7] html lang=en class=no-js ie6 lt-ie9 lt-ie8 ![endif]--
!--[if IE 7] html lang=en class=no-js ie7 lt-ie9 lt-ie8 ![endif]--
!--[if IE 8] html lang=en class=no-js ie8 lt-ie9 ![endif]--
!--[if IE 9] html lang=en class=no-js ie9 ![endif]--
!--[if gt IE 9]!-- html lang=en class=no-js !--![endif]--
headmeta http-equiv=x-ua-compatible content=IE=edge
script type=text/javascript src=//static.springer.com/spcom/js/vendor/googleapis/ajax/
libs/jquery/1.9.1/jquery.min.js/script
script type=text/javascript src=//cdn.optimizely.com/js/8200882355.js/script
script type=text/javascript id=angular-script src=//static.springer.com/spcom/js/
vendor/googleapis/ajax/libs/angularjs/1.2.17/angular.min.js/script
script type=text/javascript id=script--1908162026 src=//static.springer.com/spcom/min/
prod.js?r=201702071421-9/script
link rel=stylesheet type=text/css href=//static.springer.com/spcom/min/modern_sprcom-
cms-frontend_apress.css?r=201702071421-9 /
Chapter 2 ■ Java 9 Enhancements
44
!--[if (lt IE 9)  (!IEMobile)]link rel=stylesheet type=text/css href=//static.
springer.com/spcom/min/ielt9_sprcom-cms-frontend_apress.css?r=201702071421-9 media=screen
/![endif]--
link rel=stylesheet type=text/css href=//static.springer.com/spcom/min/print.
css?r=201702071421-9 media=print /
link rel=stylesheet type=text/css href=/spcom/css/vendor/font-awesome.min.
css?r=201702071421-9 /
!--[if lt IE 9]script type=text/javascript id=ielt9js charset=utf-8 src=//static.
springer.com/spcom/min/ielt9.js/script
■
■ Note This is an excellent example to try out in the Java 9 jShell utility. To start the utility, open a command
prompt or terminal and type jshell –add-modules java.httpclient to start the shell including the httpclient
module. This assumes that the jshell executable utility resides within the PATH.
How It Works
The new javax.httpclient module has been added to Java 9, and it comprises of high level HTTP and
WebSocket client APIs. The API provides synchronous and asynchronous implementations for the HTTP
Client, and asynchronous implementations for WebSocket. The API resides within the java.net.http package.
The HttpClient is a container for configuration information that is common to the HttpRequests type.
An HttpClient is generated by initiating an HttpRequest.Builder, passing the URI for the request, and then
calling upon the create() method. The create() method returns an immutable HttpClient. As seen in
the solution to this recipe, the client can be used to perform a number of activities, both synchronously and
asynchronously. Asynchronous requests will return a CompleteableFuture object for use. For more details
regarding the HTTP and WebSocket clients, please refer to Recipe 21-7 and Recipe 21-8.
2-7. Redirecting Platform Logs
Problem
You wish to filter logs and redirect them to a specific file if they match the specified filtering criteria.
Solution
Utilize the Java 9 Unified Logging API to filter the logs and route accordingly. In the following excerpt from
the command line or terminal, the java executable is invoked to execute a class named Recipe02_07. The
-Xlog option is specified, passing gc=debug:file=gc.txt:none. This indicates that all log messages tagged
with ‘gc’ using the ‘debug’ level should be written to the file gc.txt, and no decorations should be used.
java -Xlog:gc=debug:file=gc.txt:none Recipe02_07
This will result in the creation of a file named gc.txt in the current directory, and all log messages
pertaining to the specified –Xlog option will be written to it.
Random documents with unrelated
content Scribd suggests to you:
usurped by the Forerunners of Confusion and Anarchy, viz.: the Agitators. [The Army
appointed a Committee of Adjutators on 14th May 1647.]
My Commission as General bound me to act with [the co-operation of my] Council:
but the arbitrary and unlimited power of this new Council would act without a
General: and all that I could do, could not prevail against this stream; especially when
the Parliament itself became divided, so that the pay was withheld from the Army,
which heightened their distempers.
Then followed, Free Quarter [in November 1647]; and that brought a general
discontent through the whole nation: which gave these factious Agitators matter
enough for the carrying on of their designs; viz., To raise their own fortunes by the
ruin of others.
But now, being much troubled to see things in this condition, I did rather desire to be
a sufferer than to be a Commander: but, before I laid down my Commission, I
thought it fit to consult with some friends rather than gratify my private sense and
reason, which much desired it; especially having received it from a Public Authority,
which might justly expect to have notice of it before I laid it down. Which was the
cause of my continuing in the Army longer than I would have done (seeing I could
not have my desire granted): which did indeed preserve the Parliament for some
time, from those confusions and breakings, which afterwards Time and Confidence
emboldened these men to.
But now I shall descend to some particulars of their Agitation:
At Nottingham was the first time that I took notice of it, by the soldiers' meetings to
frame a Petition to the Parliament about their arrears [of pay]. The thing seemed just:
but, not liking the way, I spake with some Officers that were principally engaged in it;
and got it suppressed for that time.
Which was but as the cutting off of Hydra's head, which soon sprang up again
(though not so near the Head Quarters; but in more remote corners of the Army,
which I could not so timely prevent) so that they presented it to the Parliament;
which they were highly displeased with. And now falling into difference[s]; the
consequence of which proved fatal not only to the King, but also destructive to one
another. The one striving to uphold his authority: the other (who had a spirit of
unsettlement) to preserve themselves from the ruin they feared. This (with a natural
inclination to change) I believe created the thoughts of a New Government; which, in
time, attained the name of a Common Wealth: though it never arrived to the
perfection of it; being sometimes Democratical, sometimes Oligarchial, lastly Anarchial
—as indeed all the ways attaining to it seemed nothing but a Confusion.
For now the Officers of the Army were placed and displaced by the will of the new
Agitators; who, with violence, so carried all things, as it was above my power to
restrain it. This made me have recourse to my friends to get me a discharge of my
Command; so as there was a consultation with several Members of Parliament, who
met about it: but none would undertake to move it to the House, as affairs then
stood. And they perceiving that such a Motion would be unpleasing to them: which
was the answer I received from them. And further that I should satisfy myself: for it
would be the Parliament's care to compose all things in as good order as might be
most for the good and settlement of the Kingdom. But these hopes, though they
something supported my spirit; yet could not they balance the grief and trouble I had,
that I could not get my discharge. So that, if you find me carried on with this stream;
I can truly say, It was by the violence of it, and no consent of mine.
But the Army, having gotten this power and strength by correspondence with some in
Parliament (who themselves did after find it [to their disadvantage] in the end) they
[the Army] march nearer London [26th June 1647]: and, at Windsor [20th November
1647], after two days' debate in a Council of War, it was resolved to remove all out of
the House [of Commons] whom they conceived to obstruct, as they called it, the
Public Settlement.
Upon which expedition in this march, I was vehemently pressed: but here I resolved
to use a restrictive power, when I had not a persuasive one. So when the Lieutenant
General [Oliver Cromwell] and others pressed me to sign orders for marching, I still
delayed the doing of it [in November 1647]; as always dreading the consequences of
breaking Parliament, and at a time when the Kingdom was falling into a new War:
which was so near, that my delaying but three or four days giving out Orders, diverted
this humour of the Army from being Statesmen to their more proper duty of soldiers.
For, even then, Colonel Poyer declared [for the King] in Wales; great forces were
raised with the Lord Goring in Kent; and Duke [of] Hamilton (almost at the same time)
with a powerful Army of the Scots. All which set out work enough for that summer [of
1648].
This I write to shew how, by Providence, a few days' delay did prolong the Parliament
more than a year from the violent breaches that afterwards happened to them.
Here again might be mentioned the great and difficult businesses the Army went
through that year [1648]: hoping, as well aiming, it would be a good service to the
Kingdom. But, seeing the factious Party grew more insolent as success made them
more powerful, I shall forbear to relate those Actions; which would, otherwise, have
deserved a better remembrance than, in modesty, [it] were fit for me to record: and
[I] will rather punish myself here, with the continuance of the Story of the Army's
Irregularities.
But one thing, of very great concernment in all after changes, should have been
inserted before the mention of this Second War: but [it] will come in well enough in
this place, without much interruption of this Discourse, viz.:
THE KING'S REMOVAL FROM HOLMBY,
the sad consequences whereof fill my heart with grief with the remembrance of it
now; as it did then, with thoughts and care how to have prevented it.
Being then at Saffron Walden in Essex, I had notice that Cornet Joyce (an arch-
Agitator that quartered about Oxford) had [on 4th June 1647] seized on the King's
person, and removed his Quarters: and [had] given such a check to the
Commissioners of Parliament which were ordered to attend His Majesty, that they
refused to act any further in their Commission; being so unwarrantably interrupted.
But, as soon as I heard it, I immediately sent away two Regiments of Horse,
commanded by Colonel Whalley to remove this force; and to set all things again in
their due order and course.
But before he reached Holmby [or Holdenby]; the King was advanced two or three
miles [from thence] on his way towards Cambridge; attended by Joyce. Here Colonel
Whalley acquainted the King, That he was sent by the General to let him know how
much he was troubled at those great insolencies that had been committed so near his
person: and as he had not the least knowledge of it before it was done, so he had
omitted no time in seeking to remove the force; which he had orders from me to see
done. And therefore [Colonel Whalley] desired that His Majesty would be pleased to
return again to Holmby, where all things should again be settled in as much order and
quietness as they were before. And also he [Colonel Whalley] desired the
Commissioners to resume their Charge, as the Parliament had directed them: which
he had in charge also to desire them to do, from the General.
But the King refused to return; and the Commissioners refused also to act any more
as Commissioners. Which Colonel Whalley still further urged, saying, He had an
express command to see all things well settled again about His Majesty; which could
not be but by his returning again to Holmby.
Which the King said positively, He would not do.
So Colonel Whalley pressed him no further: having indeed a special direction from me
to use all tenderness and respect, as was due, towards His Majesty.
So the King came that night, or the second [6th June 1647] to Sir John Cutt's house
[at Childerley] near Cambridge: where, the next day, I waited on His Majesty. It being
also my business to persuade his return to Holmby. But he was otherwise resolved.
I pressed the Commissioners also to act again, according to the power that
Parliament had given them: which they also refused to do.
So having spent the whole day [7th June 1647] about this business; I returned to my
Quarters.
But before I took my leave of the King, he said to me, Sir, I have as great an Interest
in the Army as you. By which I plainly saw the broken reed he leaned upon.
These Agitators [or Adjutators], chameleon-like, could change into that colour which
best served their ends; and so had brought the King into an opinion that the Army
was for him: though [it was] never less for his safety and rights, than when it was
theirs.
And that it might appear what real trouble this act was to me; notwithstanding the
Army was almost wholly infected with the humour of Agitation, I called for a Court of
War, to proceed against Joyce for this high offence, and the breach of the Articles of
War. But the Officers (whether for fear of the distempered soldiers; or rather, as I
fear, from a secret allowance of what was done) made all my endeavours herein
ineffectual: and now (no punishment being able to reach them) all affairs steer after
this compass:
The King and all his Party are in hopes. Those of the Parliament, and others who kept
to their Covenant Interest, in fears. So as, for many months, Public Councils were
turned into private Junto's. Which would have been less criminal, if it had ended in
General Consent. But, on the contrary, it begat greater emulations and jealousies one
of another. So that the Army would not entrust the King any longer with the liberty he
had; nor would the Parliament suffer the King to undertake that which was properly
their work to do, viz.: [the] Settling [of] the Kingdom with its just rights and liberties.
And the Army were as jealous of the Parliament, that they [the Parliament] would not
have care enough of their [the Army's] security.
All things growing worse and worse made the King endeavour his own escape, as he
did [11th-14th November 1647]; but out of a larger confinement at Hampton Court,
to a straiter one in the Isle of Wight.
Here the Parliament treated upon Propositions of Peace with the King. But, alas, the
Envious One sowed tares that could not be rooted out, without plucking up the corn
also.
And here was the King, as the golden ball, tossed before the two great Parties; the
Parliament, and the Army: [which] grew to a great contest, which must again have
involved the kingdom in blood.
But the Army, having the greater power, got the King again into their hands;
notwithstanding all the means that could be used. The Treaty [? of Newport, ?
October 1648] was scarcely ended, before the King was seized upon by the hands of
the same person, Lieutenant Colonel Cobbett, who took him from Holmby [; and who
now removed him, on 1st December 1648, from Carisbrooke Castle to Hurst Castle].
Soon after followed his Trial.
But to prepare a way to this work [the Trial] this Agitating Council had thought first
how to remove out of the Parliament all those who were likely to oppose them in that
work; which they carried on with that secrecy as that I had not the least intimation of
it, till it was done: as some Members of the House can witness, with whom I was
met, at that very time, upon especial business, when that horrible attempt was made
by Colonel Pride upon the Parliament [on 6th December 1648]. It was so secretly
carried on that I should get no notice of it: because I always prevented those designs
when I knew of them. But by this Purging of the House, as they called it, the
Parliament was brought into such a consumptive and languishing condition as that it
could never recover again that healthful Constitution which always kept the Kingdom
in its strength and vigour.
But now, this Three-fold Cord being cut by the sword, the Trial of the King was the
easier for them to accomplish. My afflicted and troubled mind for it, and my earnest
endeavours to prevent it, will, I hope, sufficiently testify my abhorrence of the fact.
And what might they not now do to the lower shrubs, having thus cut down the
cedar? For, after this, [the] Duke [of] Hamilton, [the] Earl of Holland, and Lord Capel,
and others, were condemned to death.
But here it is fit to say something for my own vindication about my Lord Capel, Sir
Charles Lucas, and Sir George Lisle; who were prisoners at mercy upon the rendition of
Colchester: seeing some have questioned the just performance of those Articles [of
Surrender].
I (having laid siege to the town, and several assaults being made upon it) finding
their forces within [to be] much more numerous than those I had without, forced me
to take another course: blocking them up; and so, by cutting off all supplies, to bring
them to a surrender. Which, after [a] four months' siege, they were necessitated to;
and that upon mercy: they being between 3,000 and 4,000 men.
Now by Delivering upon mercy is to be understood, that some are to suffer, and the
rest to go free.
So those forementioned persons only were to suffer; and all the rest freed.
So immediately after our entrance into the town [on 26th August 1648], a Council of
War being called; those persons were sentenced to die, the rest to be quit.
Yet, on they being so resolved, I thought fit to manumit the Lord Capel, the Lord
Norwich, c. over to the Parliament (being the Civil Judicature of the Kingdom,
consisting then of Lords and Commons) as the most proper Judges of their cases:
being considerable for estates and families.
But Sir Charles Lucas and Sir George Lisle being mere Soldiers of Fortune; and falling
into our hands by the chance of war, execution was done upon them. And in this
distribution of Justice I did nothing but according to my Commission, and the trust
reposed in me.
But it may be objected that I went into the Court during the Trial.
To this, I answer. It was upon the earnest entreaties of my Lord Capel's friends; who
desired me to explain there, what I meant by Surrendering to mercy: otherwise I had
not gone, being always unsatisfied with the Court.
But for this I shall need to say no more: seeing I may as well be questioned for the
Articles of Bristol, Oxford, Exeter; or [for] any other Action in the War, as for this.
And now I have related the most remarkable things that might be alleged against me
during the prosecution of the War.
Yet one thing more requires that I should say something to it, before I conclude, viz.:
Concerning Papers and Declarations of the Army that came out in my name and the
Council of Officers. I must needs say. From the time they declared their Usurped
Authority at Triplow Heath [10th June 1647], I never gave my free consent to
anything they did: but (being then undischarged of my place) they set my hand
[signature] by way of course, to all their Papers; whether I consented or not.
And unto such failings all Authority may fall. As sometimes Kingly Authority may be
abused to their, and the Kingdom's, prejudice; sometimes, under a Parliamentary
Authority, much injury hath been done: so here, hath a General's Power been broken
and crumbled into a Levelling Faction, to the great unsettlement of the Nation.
Yet, even in this, I hope all impartial judges will interpret as a force and ravishment of
a good name; rather than a voluntary consent whereby it might make me seem to
become equally criminal. Though I must confess, if in a multitude of words, much
more in a multitude of actions, there may be some transgressions: yet, I can as truly
say, they were never designedly or wilfully committed by me.
But now, when all the power was got into the Army, they cut up the root of Kingly
Government. After this, were Engagements to relinquish the Title. Then [was] War
declared against Scotland for assisting the King [Charles II.]: and several Leagues
made with foreign Princes to confederate with their new Government, which was now
a Common Wealth, against the Kingly Power.
Seeing which, with grief and sorrow, though I had as much the love of the Army as
ever; though I was with much importunity solicited by the remaining Parliament, the
Lieutenant General [Oliver Cromwell], and other Officers and soldiers, to continue my
Command; and though I might, so long as I acted their designs, attain to the height
of power and other advantages I pleased (for so I understood from themselves): yet
(by the mercy and goodness of GOD, ever valuing Loyalty and Conscience before this
perishing felicity) I did, so long as I continued in the Army, oppose all those ways in
their counsels; and, when I could do no more, I also declined their actions, though
not their Commission I had from the Parliament, till the remaining part of it, took it
from me [25th June 1650].
Thus I have given you, in short, the sum of the most considerable things that the
World may censure me for, during this unhappy War. Yet, I hope, among many
weaknesses and failings there shall not be found crimes of that magnitude [for me] to
be counted amongst those who have done these things through ambition and
dissimulation. Hoping also that GOD will, one day, clear this Action we undertook, so
far as concerns his honour; and the integrity of such as faithfully served in it. For I
cannot believe that such wonderful successes shall be given in vain. Though cunning
and deceitful men must take shame to themselves; yet the purposes and
determination of GOD shall have happy effects to his glory, and the comfort of his
people.
Java 9 Recipes A Problemsolution Approach 3rd Ed Juneau Josh
Thomas, third Lord Fairfax.
A Short Memorial of the Northern Actions;
during the War there,
from the year 1642 till the year 1644.
did not think to have taken up my pen any more, to have written on this
subject: but that my silence seemed to accuse me of ingratitude to GOD
for the many mercies and deliverances I have had; and of injuriousness to
myself in losing the comfort of them, by suffering them to be buried in the
grave of Oblivion in my lifetime.
Wherefore I shall set down, as they come to my mind, such things wherein I have
found the wonderful assistance of GOD to me in the time of the War I was in the
North: though not in that methodical and polished manner as might have been done;
being but intended only for my own satisfaction, and the help of my memory.
As I said, in the First Part [p. 565], my father was called forth by the importunity of
the country [Yorkshire], to join with them in the defence of themselves: and [was]
confirmed by a Commission of the Parliament [by Vote on the 23rd August 1642. He
however did not actually receive the Commission till the 3rd December following.]
The first Action we had was at Bradford, where we had about 300 men. The Enemy,
having about 700 or 800 and 2 pieces of ordnance, came thither to assault us [in
October 1642]. We drew out close to the town to receive them. They had [the]
advantage of [the] ground, the town being compassed with hills; which made us
more exposed to their cannon shot, from which we received some hurt. Yet
notwithstanding, our men defended the passages, which they [the Enemy] were to
descend, so well that they got no ground of us. And now, the day being spent, they
drew off; and returned back again to Leeds.
A few days after, Captain Hotham, with 3 Troops of Horse and some Dragoons, came
to me; and then we marched to Leeds. But the Enemy, having notice of it, quitt[ed]
the town in haste; and fled to York.
And that we might have more room, and be less burthensome to our friends; we
presently advanced [in November 1642] to Tadcaster, 8 miles from York.
Now we being increased to 1,000 men, it was thought fit, for securing of the West
Riding, at least the greatest part of it, from whence our greatest supply came, to keep
the Pass at Wetherby; whither my father sent me with about 300 Foot and 40 Horse.
The Enemy's next design, from York, was to fall on my Quarters there; which was a
place very open and easy for them to do: there being so many back ways to enter in;
and friends enough to direct and acquaint them with all we did.
About six of the clock in the morning [in November 1642], they set upon us with 800
Horse and Foot. The woods thereabouts favoured them so much as that our Scouts
could get no notice of them; so as no alarm was given till they were ready to enter
the town, which they might soon do for the Guards were all asleep in houses.
For in the beginning of the War, men were as impatient of Duty as ignorant of it.
Myself only was on horseback; going out, at the other end of the town, to Tadcaster:
where my father lay.
One came running to me, and told me, The Enemy was entering the town. I presently
galloped to the Court of Guard [the Piquet], where I found not above four men at
their arms; as I remember, two Foot Sergeants and two Pike men, [who] withstood
with me when Sir Thomas Glenham, with about six or seven Commanders more,
charged us: where, after a short but sharp encounter, in which Major Carr was slain,
they retired. And in this time more of the Guard were gotten to their arms. But I must
confess I know [of] no strength, but the powerful hand of GOD, that gave them this
repulse.
Afterward they made another attempt, in which Captain Atkinson was slain.
And here again, there fell out another remarkable Providence. During this conflict, our
Magazine was blown up: which struck such a terror in the Enemy, thinking we had
cannon (which they were informed we had not), that they instantly retreated. And
though I had but a few Horse; they pursued the Enemy some miles, and took many
prisoners.
We lost about eight or ten men, whereof seven were blown up with [the] powder: the
Enemy, many more. [20]
At this time [Henry Clifford] the Earl of Cumberland commanded the Forces in Yorkshire
for the King.
But (being of a peaceable nature; and by his amiable disposition having but few
enemies, or rather because he was an enemy to few) he did not suit with their
present condition and apprehension of fears. Therefore they sent to [William
Cavendish] the Earl of Newcastle, who had an Army of 6,000 men, to desire his
assistance: which he answered by a speedy march to York.
Being now encouraged by this increase of force, they resolved to fall on Tadcaster. My
father drew all his men thither. But by a Council of War the town was judged
untenable; and that we should draw out to an advantageous piece of ground by the
town. But before we could all march out; the Enemy advanced [on 7th December
1642] so fast that we were necessitated to leave some Foot in a slight Work above
the bridge to secure our retreat.
But the Enemy pressing still on us, forced us to draw back [return back], and
maintain that ground.
We had about 900 men. The Enemy above 4,000: who, in Brigades, drew up close to
the Works, and stormed us. Our men reserved their shot till they were very near;
which then they disposed to so good purpose as forced them to retire, and shelter
themselves behind the hedges that were hard by.
And here did the fight continue from 11 a clock at noon till 5 at night, with cannon
and musket, without intermission.
They had, once, possessed a house by the bridge; which would have cut us [off] from
our reserves that were in the town: but Major General Gifford, with a commanded
party, beat them out again; where many of the enemies were slain and taken
prisoners.
They attempted at another place; but were also repulsed by Captain Lister, who was
there slain: which was a great loss, [he] being a discreet Gentleman.
And now, it growing dark, the Enemy drew off into the fields hard by; with intention
to assault us again the next day. They left that night about 200 dead and wounded
upon the place.
But our ammunition being all spent in this day's fight; we drew off that night, and
marched to Selby: and the Enemy entered, the next day [8th December 1642], into
the town [of Tadcaster]. And thus, by the mercy of GOD, were a few delivered from
an Army who, in their thoughts, had swallowed us up.
Now, the Earl of Newcastle lay between us and our friends in the West Riding; and so
[was] equally destructive to us both. But, to give them encouragement and help, I
was sent [on Friday, 9th December 1642], with about 200 Foot and 3 Troops of Horse
and some arms, to Bradford. I was to go by Ferrybridge: our intelligence being that
the Enemy was advanced yet no further than Sherburn.
But when I was within a mile of the town [i.e. Ferrybridge]; we took some prisoners
who told us That my Lord Newcastle laid at Pontefract, 800 men in Ferrybridge, and
the rest of the Army in all the towns thereabouts.
So as now, our advance, or retreat, seemed [to be] alike difficult. But, there being not
much time to demur in, a retreat was resolved on back again to Selby. 300 or 400 of
the Enemy's Horse shewed themselves in our rear, without making any attempt upon
us; and so, through the goodness of GOD, we got safe thither.
[Here, chronologically, comes in the Fight at Sherburn in Elmet, on Wednesday, 14th
December 1642, described at page 584.]
And, in three days after, [21] having better intelligence how they lay, with the same
number as before, I marched in the night by several towns where they lay, and
arrived, the next day, at Bradford: a town very untenable; but, for their good
affections, deserving all we could hazard for them.
Our first work there was to fortify ourselves; for we could not but expect strong
opposition in it: seeing there lay at Leeds 1,500 of the Enemy, and 1,200 at
Wakefield; neither above six or seven miles from us. They visited us every day with
their Horse; for ours went not far from the town, being so unequal in number: yet
they seldom returned without loss. Till, at length, our few men grew so bold; and
theirs, so disheartened: as they durst not stir a mile out of their garrison.
But while these daily skirmishes were among the Horse; I thought it necessary to
strengthen ourselves with more Foot. So, summoning the country [i.e. the West
Riding of Yorkshire], which now our Horse had given some liberty to come into us; I
presently armed them with the arms we brought along with us: so that, in all, we
were now about 800 Foot.
But being too many to lie idle, and yet too few to be in continual duty; we resolved
rather, through the assistance of GOD, to attempt them in their garrison than endure
longer this trouble. So summoning the country in again; we made a body of about
1,200 or 1,300 men: with which we marched to Leeds, and drew them up [on
Monday, 23rd January 1643] within [a] half cannon shot of their Works, in Battalia;
and then sent in a Trumpet[er] with a Summons to deliver up the town to me, for the
use of [the] King and Parliament.
They presently returned this answer, That it was not civilly done to come so near
before I sent the Summons; and that they would defend the town, the best they
could, with their lives.
So presently ordering the manner of the Storm, we all fell on at one time. The
business was hotly disputed for almost two hours: but, after, the Enemy were beaten
from their Works. The Barricadoes were soon forced open into the streets: where
Horse and Foot resolutely entering, the soldiers cast down their arms, and rendered
themselves prisoners. The Governor and some chief Officers swam the river and
escaped. One Major Beaumont was drowned, as was thought. In all, there were about
40 or 50 slain; and [a] good store of ammunition [was] taken, which we had much
want of.
But the consequence of this Action was yet of more importance. For those that fled
from Leeds and Wakefield, (for they also quitted that garrison) gave my Lord
Newcastle such an alarm at Pontefract, where he lay; as he drew all his Army back
again to York: leaving once more a free intercourse between my father [at Selby] and
me, which he had so long time cut off.
But, after a short time, the Earl of Newcastle returned again to the same Quarters [at
Pontefract]; and we to our stricter duties.
But, after some time, we found that our men must either have more room, or more
action. [This Fight at Sherburn took place on the 14th December 1642; and should
have been mentioned earlier in this Narrative.[22]] Therefore Captain Hotham and I
took a resolution, early in the morning to beat up a Quarter [Encampment] of the
Enemy that lay at [Church] Fenton. But they being gone, we marched towards
Sherburn [in Elmet]; intending only to give them an alarm there.
But they might see us, a mile or two, march over a plain common which lay by the
Town; and therefore had sent about 20, or 30, Horse to guard a Pass near the town. I
having the Van (For, at this time we [Fairfax and Hotham] commanded our Troops
distinct one from another; both making 5 Troops of Horse and 2 of Dragoons), I told
him, If he would second me, I would charge those Horse; and if they fled, I would
pursue them so close[ly] as to get into the town with them. He promised to second
me. I went to the head of my Troops, and presently charged them: who fled, and we
pursued [them] close to the Barricado. But they got in, and shut it upon us; where
my horse was shot at the breast. We so filled the lane; being strait [narrow] that we
could not retreat without confusion, and danger of their falling in our rear. So we
stood to it; and stormed the Work with pistol and sword. At the end of the Barricado,
there was a straight passage for one single horse to go in. I entered there, and others
followed one by one. Close at one side of the entrance stood a Troop of Horse: but so
soon as eight or ten of us got in they fled. And by this time, the rest of our men had
beaten them from their Barricado, and entered the town, which soon cleared the
streets, and pursued those that fled. And now my horse, which was shot in the lane,
fell down dead under me: but I was presently mounted again.
They in the towns about having taken the alarm, now made us think of securing our
retreat with the prisoners we had gotten: and some of them [were] very
considerable; among whom was Major General Windham. But we scarce[ly] got into
good order before General Goring came, with a good body of Horse, up to us: and as
we marched on, he followed close in the rear, without [our] receiving any hurt; only
my Trumpet[er] had his horse shot close by me. So we returned again to Selby.
But though this could not free us wholly from a potent Enemy; yet we lay more
quietly by them a good while after.
In this recess of action, we had several treaties [negotiations] about prisoners. And
this I mention the rather, for that Captain Hotham here began to discover his intention
of leaving the Parliament's Service, by making conditions for himself with the Earl of
Newcastle (though [it was] not discovered till a good while after): which had almost
ruined my father, and the forces that were with him.
For, being now denied help and succour from Hull and the East Riding; he was forced
to forsake Selby, and retire to Leeds and those western parts where [I] myself was.
But to make good this retreat, I was sent to, to bring what men I could to join with
him at Sherburn. For Newcastle's forces lay so, as he might easily intercept us in our
way to Leeds: which he had determined [to do], and to that end lay with his Army on
Clifford Moor; having perfect intelligence of our march.
But while my father, with 1,500 men ordnance and ammunition, continued [on 2nd
April 1643] his way from Selby to Leeds; I, with those I brought to Sherburn,
marched a little aside, between my Lord Newcastle's Army and ours. And to amuse
[deceive] them the more, [I] made an attempt upon Tadcaster: whither they had 300
or 400 men; who presently quitted the town, and fled to York. Here we stayed three
or four hours sleighting [destroying] the Works.
This put Newcastle's Army to a stand, which was on their march to meet us: thinking
that he was deceived in his intelligence; and that we had some other design upon
York.
He presently sent back the Lord Goring, with 20 Troops of Horse and Dragoons, to
relieve Tadcaster. We were newly drawn off when they came. Goring pressed over the
river to follow us.
But seeing we were far unequal to him in Horse, for I had not above 3 Troops; and
[having] to go over Bramham Moor, a large plain: I gave direction to the Foot to
march away, while I stayed with the Horse to interrupt the Enemy's passage in those
narrow lanes that lead up to the Moor. Here was much firing at one another. But, in
regard of their great number, as they advanced we were forced to give way: yet had
gained by it sufficient time for the Foot to be out of danger.
But when we came up to the Moor again, I found them where I left them: which
troubled me much, the Enemy being close upon us, and a great plain yet to go over.
So [I] marched the foot in two Divisions, and the Horse in the rear. The Enemy
followed, about two musket shot from us, in three good bodies: but yet made no
attempt upon us. And thus we got well over the open campania.
But having again gotten to some little enclosures, beyond which was another Moor,
called Seacroft Moor [now called Whin Moor. It is about five miles from Leeds], much
less than the first. Here our men thinking themselves more secure, were more
careless in keeping order; and while their officers were getting them out of houses,
where they sought for drink, [it] being an exceedingly hot day; the Enemy got,
another way, as soon as we, on to the Moor. But we had almost passed this plain also.
They [the Royalists] seeing us in some disorder, charged us both in Flank and Rear.
The countrymen presently cast down their arms, and fled. The Foot soon after:
which, for want of pikes, were not able to withstand their Horse. Some were slain;
and many taken prisoners. Few of our Horse stood the charge. Some Officers, with
me, made our retreat with much difficulty; in which Sir Henry Foulis had a slight hurt.
My Cornet was taken prisoner. Yet [we] got to Leeds about two hours after my father,
with those forces with him, was arrived safe thither.
This was one of the greatest losses we ever received. Yet was it a great Providence
that it was a part, and not the whole, [of the] Force which received this loss: it being
the Enemy's intention to have fought us that day with their whole Army, which was,
at least, 10,000 men; had not the Attempt at Tadcaster put a stand to them. And so
concluded that day with this storm that fell on us.
But now, being at Leeds, it was thought fit to possess some other place also:
wherefore I was sent to Bradford, with 700 or 800 Foot and 3 Troops of Horse. These
two towns being all the garrisons we had. At Wakefield, six miles off, lay 3,000 of the
Enemy: but yet [we] had not much disturbance from them.
Being most busied about releasing our prisoners that were taken at Seacroft Moor,
most of them being countrymen [Yorkshire peasants]; whose wives and children were
still importunate for their release: which was as earnestly endeavoured by us; but no
conditions would be accepted. So their continual cries, and tears, and importunities
compelled us to think of some way to redeem these men: so as we thought of
attempting Wakefield; our intelligence being that the Enemy had not above 800 or
900 men in the town.
I acquainted my father with our design: who approved of it; and sent [to Bradford]
some men from Leeds; which enable us to draw out 1,100 Horse and Foot.
So upon Whit-Sunday [21st May 1643], early in the morning, we came before the
town. But they had notice of our coming, and had manned all their Works, and set
about 800 Musketeers to line the hedges about the town: which made us now doubt
our intelligence; which was too late. Notwithstanding, after a little consultation, we
advanced, and soon beat them back into the town; which we stormed in three places.
After two hours' dispute, the Foot forced open a Barricado, where I entered with my
own Troop. Colonel Alured, and Captain Bright, followed with theirs. The street which
we entered was full of their Foot: which we charged through, and routed; leaving
them to the Foot which followed close behind us. And presently we were charged
again with Horse led by General Goring: where, after a hot encounter, some were
slain; and [he] himself taken prisoner by [the brother of] Colonel Alured.
And I cannot but here acknowledge GOD's goodness to me this day: who being
advanced a good way single [alone] before my men, having a Colonel and a
Lieutenant Colonel, who had engaged themselves to be my prisoners, only with me;
and many of the enemies between me and my men, I light[ed] on a Regiment of Foot
standing in the Market Place.
Thus encompassed, and thinking what to do; I espied a lane which I thought would
lead me back to my men again. At the end of this lane, there was a Corps du Guard
[Piquet] of the Enemy's, with 15 or 16 soldiers; who were then just quitting it, with a
Serjeant leading them off: whom we met. Who, seeing their [two] Officers, came up
to us; taking no notice of me. They asked them, What they would have them do? for
they could keep the Work no longer; because the Roundheads, as they called them,
came so fast upon them.
But the Gentlemen, who had passed their words to me to be my true prisoners, said
nothing. So, looking upon one another, I thought it not fit now to own them; as so
much less to bid the rest to render themselves to me: so, being well mounted, and
seeing a place in the Work where men used to go over, I rushed from them, seeing
no other remedy, and made my horse leap over the Work. And so, by a good
Providence, got to my men again: who, before I came, had, by the direction of Major
General Gifford, brought up a piece of ordnance, and planted it in the Churchyard,
against the body that stood in the Market Place; who presently rendered themselves.
All our men being got into the town, the streets were cleared, [and] many prisoners
taken. But the Horse got off almost entire. But this seemed the greater mercy when
we saw our mistake: now finding 3,000 men in the town, [and] not expecting half the
number. We brought away 1,400 prisoners, 80 Officers, 28 Colours; and [a] great
store of ammunition, which we much wanted.[23]
But seeing this was more a Miracle than a Victory; more the effect of GOD's divine
power than human force; and more his Providence than the success of our prudence
in making so hazardous an attempt: let the honour and praise of it be His only!
After this, we exchanged our men that were prisoners, with these: and were freed, a
good while; from any trouble or attempt from [the] Enemy.
But then again it pleased GOD to mix water with our wine; and to bring us into a
better condition by the brinks of ruin and destruction.
Hitherto, through His mercy, we had held up near[ly] two years against a potent
Army: but they finding us now almost tired, with continual Services; treacherously
used by our friends; and in want of many things necessary for support and defence—
the Earl of Newcastle marched with an Army of 10,000 or 12,000 men to besiege us;
and resolved to sit down before Bradford, which was a very untenable place.
My father drew all the forces he could spare out of the garrisons hither.
But seeing it impossible to defend the town but by strength of men; and not [having]
above ten or twelve days' provisions for so many as were necessary to keep it: we
resolved [on 29th June 1643] the next morning, very early, with a party of 3,000
men, to attempt his whole Army, as they lay in their Quarters, three miles off; hoping
thereby, to put him into some distraction; which could not, by reason of the unequal
numbers, be done any other way.
For this end, my father appointed four of the clock next morning [30th June 1643] to
begin the march. But Major General [John] Gifford, who had the ordering of the
business, so delayed the execution of it that it was seven or eight before we began to
move: and not without much suspicion of treachery in it; for when we came near the
place we intended, the Enemy's whole Army was drawn up in Battalia.
We were to go up a hill to them, which our Forlorn Hope [or Advanced Guard] gained
by beating theirs into their Main Body; which was drawn up half a mile further, upon a
plain called Adderton [the correct spelling is Adwalton] Moor. [It is also spelt
Atherston and Atherton.]
We, being all up the hill, drew into Battalia also. I commanded the Right Wing, which
was about 1,000 Foot and 5 Troops of Horse; Major General [John] Gifford, the Left
Wing, which was about the same number. My father commanded all in chief.
We advanced through the enclosed grounds till we came to the Moor; beating the
Foot that lay in them to their Main Body.
10 or 12 Troops of Horse charge us in the Right Wing [which was at the head of
Warren's Lane]. We kept [to] the enclosures, placing our Musketeers in the hedges
next the Moor; which was a good advantage to us, that had so few Horse.
There was a gate, or open place, to the Moor: where five or six might enter abreast.
Here they strove to enter: we, to defend. But, after some dispute, those that entered
the pass found sharp entertainment; and those that were not yet entered, as hot
welcome from the Musketeers, that flanked them in the hedges. All, in the end, were
forced to retreat; with the loss of Colonel Howard, who commanded them.
The Left Wing, at the same time, was engaged with the Enemy's Foot. Ours gained
ground of them.
The Horse came down again, and charged us: being about 13 or 14 Troops. We
defended ourselves as before; but with much more difficulty, many having got in
among us: but [they] were beat[en] off again, with some loss; and Colonel Herne,
who commanded that party, was slain. We pursued them [back] to their cannon.
And here I cannot omit a remarkable passage of Divine Justice. Whilst we were
engaged in the fight with those Horse that entered the gate, four soldiers had
stripped Colonel Herne naked; as he lay dead on the ground, [and] men still fighting
round about him: and so dextrous were these villains, as they had done it, and
mounted themselves again, before we had beaten them off. But after we had beaten
them to their ordnance, as I said; and [were] now returning to our ground again; the
Enemy discharged a piece of cannon in our rear. The bullet fell into Captain Copley's
Troop, in which these four men were: two of whom were killed; and some hurt or
mark remained on the rest, though dispersed into several Ranks of the Troop, which
was [the] more remarkable.
We had not yet Martial Law amongst us: which gave me a good occasion to reprove
it; by shewing the soldiers the sinfulness of the act, and how GOD would punish when
men wanted power to do it.
This charge, and the resolution our soldiers shewed in the Left Wing, made the
Enemy think of retreating. Orders were given for it; and some marched off the Field.
Whilst they were in this wavering condition, one Colonel Skirton, a wild and desperate
man, desired his General to let him charge [on our Left Wing] once more, with a
Stand of Pikes. With which he brake in upon our men; and they not [being] relieved
by our Reserves, ([which were] commanded by some ill-affected Officers; chiefly
Major General Gifford, who did not his part as he ought to do), our men lost ground:
which the Enemy seeing, pursued this advantage by bringing on fresh troops. Ours,
being herewith discouraged, began to flee; and so [were] soon routed.
The Horse also charged us again. We, not knowing what was done in the Left Wing;
our men maintained their ground till a command came for us to retreat: having scarce
any way now to do it; the Enemy being almost round about us, and our way to
Bradford cut off. But there was a lane [Warren's Lane] in the field we were in, which
led to Halifax: which, as a happy Providence, brought us off without any great loss;
save of Captain Talbot and twelve more, which were slain in this last encounter.
Of those [on the Left Wing] that fled, there were about 60 killed, and 300 taken
prisoners.
This business, having such ill success, our hopes of better could not be much:
wanting all things that were necessary for defence, and [no] expectations of helps
from any place.
The Earl of Newcastle presently lay siege to the town [of Bradford]: but before he had
surrounded it, I got in with those men I brought from Halifax.
I found my father much troubled; having neither a Place of Strength to defend
ourselves in, nor a garrison in Yorkshire to retreat to. For [Sir John Hotham the Elder,]
the Governor of Hull had declared himself, If we were forced to retreat thither, that he
would shut the gates on us.
But, while he was musing on these sad thoughts, a messenger was sent from Hull to
let him know, The townsmen had secured [taken prisoner] the Governor [on the
morning of the 29th June 1643]; and if he had any occasion to make use of that
place, for they were sensible of the danger he was in, he should be very readily and
gladly received [there]. Which news was joyfully received, and acknowledged as a
great mercy of GOD to us: yet was it not made use of till a further necessity
compelled it.
So my father, having ordered me to stay here [at Bradford] with 800 Foot and 60
Horse: he intruded [retired] that night [of 30th June 1643] for Leeds, to secure it.
Now Newcastle, having spent three or four days in laying his Quarters about the town;
they brought down their cannon: but needed to raise no batteries, for the hills, within
half [a] musket shot, commanded all the town; which [cannon], now being planted in
two places, shot furiously upon us. [They] making also Approaches; which made us
spend very much [ammunition].
Our little store was not above five and twenty, or thirty, barrels of powder at the
beginning of the siege: yet, notwithstanding, the Earl of Newcastle sent a Trumpet[er]
to offer us Conditions; which I accepted so they were honourable for us to take, and
safe for the inhabitants.
Upon which, two Captains were sent to treat with him, and a Cessation [was agreed
upon] during the time; but he continued working still, contrary to [the] agreement:
whereupon I sent for the Commissioners again, suspecting a design of attempting
something against us; but he returned them not till eleven a clock at night [of 1st July
1643], and then with a slight answer.
Whilst they were delivering it to us, we heard great shooting of cannon and muskets.
All ran presently to the Works, which the Enemy was storming. Here, for three-
quarters of an hour, was very hot service: but, at length they retreated.
They made a second attempt: but were also beaten off.
After this, we had not above one barrel of powder left; and no Match. So I called the
Officers together: where it was advised and resolved [evidently about 1 a.m. on the
2nd July 1643] to draw off presently, before it was day; and by forcing a way, which
we must do (they having surrounded the town), [in order] to retreat to Leeds.
Orders were despatched, and speedily put in execution.
The Foot, commanded by Colonel Rogers, was sent out, through some narrow lanes;
who were to beat up the Dragoons' Quarters [Encampment]; and so to go on to
Leeds.
[I] myself, with some other Officers, went with the Horse, which were not above 50,
in an opener way.
Here I must not forget to mention my Wife, who ran great hazards with us in this
retreat as any others; and with as little expression of fear: not from any zeal or
delight, I must needs say, in the War; but through a willing and patient suffering of
this undesirable condition.
But now I sent two or three Horsemen to discover what they could of the Enemy:
which presently returned, and told us, There was a Guard of Horse close by us.
Before I had gone forty paces, the day beginning to break, I saw them on the hill
above us; being about 300 Horse.
I, with some 12 more, charged them. Sir Henry Foulis, Major General Gifford, and
myself, with three more [i.e., 6 out of 13] brake through. Captain Mudd was slain: and
the rest of our Horse, being close by, the Enemy fell upon them, taking most of them
prisoners; amongst whom my Wife was, the Officer behind whom she was [on
horseback] being taken.
I saw this disaster; but could give no relief. For after I was got through, I was in the
Enemy's Rear alone; for those that had charged also through, went on to Leeds;
thinking I had done so too.
But being unwilling to leave my company: I stayed till I saw there was no more in my
power to do; but to be made a prisoner with them. Then I retired to Leeds.
The like disorder fell amongst the Foot that went the other way, by a mistake. For
after they had marched a little way, the Van fell into the Dragoons' Quarters
[Encampment], clearing the way. But through a cowardly fear of him that commanded
those men who were in the Rear; [he] made them face about, and march again into
the town [of Bradford]: where, the next day [2nd July 1643], they were all taken
prisoners.
Only 80, or thereabouts, of the Front, which got through, came to Leeds; all mounted
on horses which they had taken from the Enemy: where I found them when I came
thither; which was some joy to them, all concluding I was either slain or taken
prisoner.
I found all in great distraction here [i.e., at Leeds].
The Council of War was newly risen, where it was resolved to quit the town, and
make our retreat to Hull; which was 60 miles off, and many garrisons of the Enemy
on the way. Which, in two hours time was done: for we could expect no less than that
the Enemy should presently send Horse to prevent it. For they had 50, or 60, Troops
within three miles.
But we got well to Selby; where there was a ferry: and, hard by, a garrison at
Cawood.
My father, being a mile before, with a few men getting over the ferry; word came to
us that he was in danger to be taken. I hastened to him with about 40 Horse: the rest
[of the Horse] coming on after in some disorder. He was newly got into the boat.
The Enemy, with 3 Cornets of Horse, entering the town; I was drawn up in the Market
Place, just before the street they came down. When they were almost half come into
the Market Place, they turned on the right hand.
With part of my Troop, I charged them in the Flanks; [and] so divided them. We had
the chase of them down the long street that goes to Brayton.
It happened, at the same time, [that] those men [which] I left behind, were coming
up that street: [but] being in disorder, and under [the] discouragements of the
misfortunes of many days before, [they] turned about, and gave way; not knowing
that we were pursuing them in the rear. [That is, there were tearing along the
Brayton road; (1) Fairfax's disordered Cavalry; then (2) the Royalist Cavalry; followed
by (3) Fairfax with a part of his Troop.]
At the end of this street, was a narrow lane which led to Cawood. The Enemy strove
to pass away there; but [it] being strait [narrow], caused a sudden stop: where we
were mingled one among another.
Here I received a shot in the wrist of my arm, which made the bridle fall out of my
hand: which [wound], being among the nerves and veins, suddenly let out such a
quantity of blood as that I was ready to fall from my horse. So taking the reins in the
other hand, wherein I had my sword; the Enemy minding nothing so much as how to
get away: I drew myself out of the crowd, and came to our men that turned about;
which were standing hard by. Seeing me ready to fall from my horse, they laid me on
the ground: and [I] now, [being] almost senseless. My Chirurgeon came seasonably,
and bound up the wound, [and] so stopped the bleeding.
After a quarter of an hour's rest there, I got on horseback again.
The other part of our Horse also beat the Enemy to Cawood back again, that way
they first came to us.
So, through the goodness of GOD, our passage here was made clear. Some went over
the ferry, after my father.
Myself, with others, went through the Levels [of the Fen Country, in North
Lincolnshire; and south of the Humber] to Hull. But it proved a very troublesome and
dangerous passage; having oft interruptions from the Enemy; sometimes in our front,
sometimes in our rear.
And now I had been at least twenty hours on horseback, after I was shot [at Selby],
without any rest or refreshment: and as many hours before. [40 hours from 1 a.m. on
the night of 2nd July 1643, when Fairfax decided to cut his way out of Bradford,
would make it about 5 p.m. of the 3rd July 1643.]
And, as a further addition to my affliction, my daughter [Mary, who afterwards
married George Villiers, second Duke of Buckingham, see p. 611], not above five years
old, being carried before her maid, endured all this retreat on horseback: but, Nature
not [being] able to hold out any longer, [she] fell into frequent swoonings; and [was],
in appearance, ready to expire her last [breath]. And having now passed the Trent
[and therefore come into North Lincolnshire], and seeing a house not far off, I sent
her, with her maid only, thither: with little hopes of seeing her any more alive; but
intending, the next day, to send a ship from Hull for her.
So I went on to Barton [upon Humber: nearly opposite Hull]; having sent before to
have a ship ready against my coming thither.
Here I lay down a little to rest; if it were possible to find any in a body so full of pain;
and [in] a mind so full of anxiety and trouble. Though I must acknowledge it, as the
infinite goodness of GOD, methought my spirits were nothing at all discouraged from
doing still that which I thought to be my work and duty.
But I had not laid [down] a quarter of an hour before the Enemy came close to the
town [of Barton]. I had now not above 100 Horse with me. We went to the ship;
where, under the covert of her ordnance, we got all our men and horses aboard.
So passing [the] Humber, we arrived at Hull; our men faint and tired: [and I] myself
having lost all, even to my shirt; for my clothes were made unfit to wear, with rents
and the blood which was upon them. Considering which, in all humility and reverence,
I may say, I was in Job's condition when he said, Naked came I out of my mother's
womb, and naked shall I return thither. The Lord gave, and the Lord hath taken away.
Blessed be the Name of the Lord. [Job i. 21.]
But GOD, who is a GOD of Mercy and Consolation, doth not always leave us in
distress.
I having sent a ship, presently after I came into the town, for my daughter: she was
brought, the next day [4th July 1643], to Hull; pretty well recovered of her long and
tedious journey.
And, not many days after, the Earl of Newcastle sent my Wife back again, in his coach,
with some Horse to guard her: which generosity gained more than any reputation he
could have gotten in detaining a Lady prisoner upon such terms.
And many of our men, which were dispersed in this long retreat, came hither again to
us.
Our first business now, was to raise new forces: which, in a short time, were about
1,500 Foot and 700 Horse.
The town [of Hull] being little; I was sent to Beverley with the Horse and 600 Foot.
But my Lord [of] Newcastle, who now looked upon us as inconsiderable, was marched
with his whole Army into Lincolnshire: only leaving some few garrisons at York and
other few places. He took in Gainsborough and Lincoln; and intended [to take] Boston
next, which was the Key of the Associated Countries [Counties]. For his Orders, which
I have seen, were to go into Essex; and block up London on that side.
But we, having laid a great while [from 4th July to 26th August 1643] still, were now
strong enough in the Field for those forces that remained in the Country [Yorkshire].
So we sent out a good party to make an attempt upon Stamford Bridge, near York.
But the Enemy, upon the alarm, fled thither [i.e. to York]; which put them all there in
such a fear as they sent earnestly to desire him to return, or the Country [Yorkshire]
would again be lost: for the Lord Fairfax had considerable forces.
Upon which, he returned again into Yorkshire; and, not long after, came to besiege
Hull.
I, lying then at Beverley in the way of his march, finding that we were not able to
maintain such an open place against an Army, desired Orders from my father to retire
back to Hull.
But the Committee there (having always more mind of raising money, than to take
care of the Soldiers; yet these [Committee] Men had the greatest share in command
at this time) would not let any Orders be given for our retreat; and [it were] unfit for
us to return without [them].
The Enemy marcheth from York, with his whole Army, towards us. Retreat, we must
not. Keep the town, we could not. So to make our retreat more honourable, and
useful both; I drew out all the Horse and Dragoons toward the Enemy, and stood,
drawn up by a wood side, all that night.
The next morning [2nd September 1643], by day[time], our Scouts, and theirs, fired
on one another. They march[ed] on with their whole body; which was about 4,000
Horse and 12,000 Foot.
We stood till they were come very near [to] us. I then drew off (having given
directions before for the Foot to march away toward Hull), thinking to make good the
retreat with the Horse.
The Enemy, with a good party, were upon our rear. The lane being but narrow, we
made good shift with them till we got into Beverley, and shut the gates: which we
had scarce time to do; they being so close upon us. But, in this business, we lost
Major Layton, and not above 2 more.
The Enemy, not knowing what forces we had in the town, stayed till the rest of the
Army came up; which was about a mile behind. This gave our Foot some advantage
in their retreat: it being 5 miles to Hull, on narrow banks [and] so fittest for our Foot.
I sent the Horse by Cottingham, an opener road; who got well thither.
But they [the Royalists] overtook the Foot: which, notwithstanding, made good their
retreat till we got to a little bridge, 2 miles from Hull; where we made a stand.
The Enemy following close, our men here gave them a good volley of shot; which
made them draw back, and advance no further. So, leaving a small Guard at the
bridge, we got safe to Hull.
Thus not only for want of military skill in the Gentlemen of the Committee; but, to say
no more, for want of good nature: we were exposed to this trouble and danger.
My Lord of Newcastle now lay siege to Hull, but at a great distance. The sluices being
open, drowned the land two miles about the town: yet upon a bank, which was the
highway, he approached so near as to shoot cannon shot at random into the town;
which were, for the most part, fiery bullets. But the diligence and care of the
Governor (who caused every inhabitant to watch his own house; and wheresoever
they saw these bullets fall, to be ready to quench them) prevented the danger.
Our Horse was now useless: and many [horses] died every day; having nothing but
salt water about the town.
I was therefore sent with the Horse, over [the Humber] into Lincolnshire, to join with
[Edward Montagu,] the Earl of Manchester's forces; which were then commanded by
Major General [Oliver] Cromwell: who received us at our landing, with his troops.
Sir John Henderson lay within three or four miles of this place with 5,000 men, to
prevent our conjunction: but durst not attempt [it].
He marched three or four days near to us: but, for want of good intelligence, we did
not know so much. For I altogether trusted to the care of our new friends, being a
stranger in those parts: till one morning [9th October 1643] he set upon our Guards
at Horncastle; which, being but newly raised in that Country [Lincolnshire], fled
towards Lincoln, without giving any alarm to our Quarters, who lay dispersed and
secure.
But Sir John Henderson, marching slowly with his Army, gave the alarm to some of our
Quarters; which was soon taken by the rest: but, with some disorder, before we could
get into a considerable body. My Lord Willoughby with his Horse, and my Dragoons
commanded by Colonel Morgan, brought up the Rear. After some skirmishes, we
lodged that night all in the Field.
And, next day [10th October 1643], the Earl of Manchester came to us with his Foot.
The day following [11th October 1643], we advanced again towards the Enemy; and
choosing a convenient ground to fight on, we drew up the Army there. The Enemy did
so on the side of another hill close by, having a little plain betwixt us.
Lieutenant General [Oliver] Cromwell had the Van [of Horse]; I, the Reserve [of
Horse]: my Lord [of] Manchester all the Foot. After we had faced one another a little
while; the Forlorn Hopes [Advanced Guards] began the fight. Presently the [Main]
Bodies met in the plain: where the fight was hot for half an hour; but then we forced
them to a rout. Above 200 killed, and 2000 taken prisoners. This was the issue of
Horncastle Fight, or, as some call it, Winceby Fight.
At the same instant, we heard great shooting of ordnance towards Hull: which was a
sally my father made [out of the town] upon my Lord of Newcastle's Trenches; who
drew out most part of his Army to relieve them. But our men charged so resolutely as
they possessed themselves of the cannon; and so pursued their advantage as [they]
put the enemy into a total rout. Upon which, he raised the Siege, and returned again
to York.
These two defeats together, the one falling heavy on the Horse, the other on the
Foot, kept the Enemy all that Winter [of 1643-1644] from attempting anything.
And we, after the taking of Lincoln, settled ourselves in Winter Quarters.
But, in the coldest season of it, I was ordered by the Parliament to go and raise the
Siege of Nantwich; which the Lord Byron, with the Irish Army, had reduced to great
extremity.
I was the most unfit of all the forces; being ever the worst paid; my men sickly, and
almost naked for want of clothes. I desired the Parliament that they would be pleased
to supply these wants: not to excuse myself, as some who had no will to stir, though
well enough accommodated with all these; and a business of so much importance.
But their answer was a positive direction to march; for it would admit of no delay:
which indeed was as grievous to me as that injunction was to the Israelites, to make
bricks without straw.
But, foreseeing I should have such a return to my desires, I had, seeing the necessity
of the business, upon my own credit got so much cloth as clothed 1,500 men: and
[they were] all ready to march when these Orders came to me.
So, the 29th of December [1643], we got forwards from Falkingham in Lincolnshire to
Nantwich, with 1,800 Horse and 500 Dragoons; and a Power to call the Regiments [of
Foot] of Lancashire and Cheshire to make up the body of the Army. But it was not a
little trouble to me, when I came to Manchester, to find some of them 30, some 40
miles distant: besides the disaffection of some of their Colonels, who went as their
peculiar [individual] safety or Interest swayed them. But, finding more readiness in
the inferior Officers and common soldiers, I got up, in a few days, near[ly] 3,000
Foot.
With this Army, we marched [from Manchester, on the 21st January 1644] to
Nantwich; which was at the point of surrendering.
When we were within two days' march, I had intelligence that the Lord Byron had
drawn off his Siege; and intended to meet us in the Field. I put my men into the order
I intended to fight [in]; and so continued my march till we came within 3 miles of the
town.
There, was a Pass kept with about 250 men. I sent Colonel Morgan, with his
Dragoons, to beat them off: in which, his brother, who was his Lieutenant, was slain.
The Major who commanded the other party, with some others, were taken prisoners.
We marched on till we came within cannon shot of their Works, where half of their
Army was drawn up. The river [Weaver], which runs through the town, being raised
with the melting of the snow, hindered, as we were informed, those that lay on the
other side of the town from joining with them.
We called a Council [of War, on 25th January 1644] wherein it was debated, Whether
we should attempt those in their Works [Entrenchments], being divided from the rest
of the Army: or march into the town and relieve them; and, by increase of more force
be better able, the next day [26th January 1644] to encounter them.
The latter was resolved on. So, making a way with [the] Pioneers through the hedges,
we marched to[wards] the town.
But, after we had gone a little way, word came that the Enemy were in the Rear. So,
facing about two Regiments [of Foot] and my own Regiment of Horse, commanded by
Major Rousby, we relieving those that were already engaged. And so the fight began
on all sides. These that fell on our Rear were those that lay [on] the other side of the
town; which had passed the river [Weaver]. Those that were drawn up under their
Works [about Acton Church], fell upon our Van, which was marching to the town.
Thus was the battle divided; there being a quarter of a mile betwixt us.
In the division first engaged, our Foot, at the beginning, gave a little ground: but our
Horse recovered this, by beating the Enemy's Horse out of the lanes that flanked our
Foot; which did so encourage our men as they gained now of the Enemy, so as they
made them retire from hedge to hedge till, at length, they were forced to fly to their
Works [Entrenchments]. But their Horse retreated in better order towards Chester,
without much loss.
Our other Wing [the Van], being assisted from the town, who sallied out with 700 or
800 Musketeers, beat the Enemy also back into the same Works [at Acton Church];
which we presently surrounded. [Where, as Sir T. Fairfax said in his despatch, they
were caught as in a trap.]
But, being in great disorder and confusion, [they] sooner yielded themselves
prisoners; with all their Chief Officers, arms, Colours, and ammunition.
Thus, by the mercy of GOD, was this victory obtained: being yet the more signal in
that we were not to deal with young soldiers, but with men of great experience; and
an Army which had ever been victorious.
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

More Related Content

PDF
Learn Advanced Java Programming With Beginners Md Pulok
PDF
Beginning Java with WebSphere Expert s Voice in Java Janson Robert W
PPTX
Unit1- OOPJ Chapter-1 Object Oriented Programming JAVA.pptx
PPTX
JAVA ALL 5 MODULE NOTES.pptx
PPTX
Features of java unit 1
PDF
Java Introduction | PDF
PDF
Core Java-1 (1).pdf
Learn Advanced Java Programming With Beginners Md Pulok
Beginning Java with WebSphere Expert s Voice in Java Janson Robert W
Unit1- OOPJ Chapter-1 Object Oriented Programming JAVA.pptx
JAVA ALL 5 MODULE NOTES.pptx
Features of java unit 1
Java Introduction | PDF
Core Java-1 (1).pdf

Similar to Java 9 Recipes A Problemsolution Approach 3rd Ed Juneau Josh (20)

PPTX
Java ms harsha
PPT
Java presentation
PPTX
Great cup of java
PDF
perl-java
PDF
perl-java
PDF
Java course in Chandigarh.pdf
PDF
Java In Easy Steps Covers Java 9 1st Edition Mike Mcgrath
PPT
Chapter 1 introduction to java technology
PDF
TechSearchWeb.pdf
PDF
Technology Tutorial.pdf
PDF
Java - At a glance
PPTX
best java training institute in Chandigarh ppt
PPT
Core Java Slides
PPTX
Java fx
PDF
TechSearchWeb Tutorials.pdf
PPT
Core java slides
PDF
Advanced Java Online Training - Naresh IT
PPTX
DIT 206 LECTURE 2 - Features of the Java Programming Language copy.pptx
PPTX
Introduction to Java in cs engineering .pptx
Java ms harsha
Java presentation
Great cup of java
perl-java
perl-java
Java course in Chandigarh.pdf
Java In Easy Steps Covers Java 9 1st Edition Mike Mcgrath
Chapter 1 introduction to java technology
TechSearchWeb.pdf
Technology Tutorial.pdf
Java - At a glance
best java training institute in Chandigarh ppt
Core Java Slides
Java fx
TechSearchWeb Tutorials.pdf
Core java slides
Advanced Java Online Training - Naresh IT
DIT 206 LECTURE 2 - Features of the Java Programming Language copy.pptx
Introduction to Java in cs engineering .pptx
Ad

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
master seminar digital applications in india
PPTX
Cell Types and Its function , kingdom of life
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Cell Structure & Organelles in detailed.
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Complications of Minimal Access Surgery at WLH
PDF
Pre independence Education in Inndia.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Supply Chain Operations Speaking Notes -ICLT Program
master seminar digital applications in india
Cell Types and Its function , kingdom of life
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Sports Quiz easy sports quiz sports quiz
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Cell Structure & Organelles in detailed.
TR - Agricultural Crops Production NC III.pdf
Insiders guide to clinical Medicine.pdf
Microbial disease of the cardiovascular and lymphatic systems
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Complications of Minimal Access Surgery at WLH
Pre independence Education in Inndia.pdf
Ad

Java 9 Recipes A Problemsolution Approach 3rd Ed Juneau Josh

  • 1. Java 9 Recipes A Problemsolution Approach 3rd Ed Juneau Josh download https://ebookbell.com/product/java-9-recipes-a-problemsolution- approach-3rd-ed-juneau-josh-55586392 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Java 9 Recipes A Problemsolution Approach Josh Juneau https://ebookbell.com/product/java-9-recipes-a-problemsolution- approach-josh-juneau-5857764 Modern Java Recipes Simple Solutions To Difficult Problems In Java 8 And 9 Ken Kousen https://ebookbell.com/product/modern-java-recipes-simple-solutions-to- difficult-problems-in-java-8-and-9-ken-kousen-6732954 Java 9 Modularity Revealed Project Jigsaw And Scalable Java Applications 1st Ed Alexandru Jecan https://ebookbell.com/product/java-9-modularity-revealed-project- jigsaw-and-scalable-java-applications-1st-ed-alexandru-jecan-55591686 Java 9 Dependency Injection Write Loosely Coupled Code With Spring 5 And Guice Patel https://ebookbell.com/product/java-9-dependency-injection-write- loosely-coupled-code-with-spring-5-and-guice-patel-56225262
  • 3. Java 9 Revealed For Early Adoption And Migration Sharan Kishori https://ebookbell.com/product/java-9-revealed-for-early-adoption-and- migration-sharan-kishori-22038542 Java 9 Data Structures And Algorithms Debasish Ray Chawdhuri https://ebookbell.com/product/java-9-data-structures-and-algorithms- debasish-ray-chawdhuri-24542320 Java 9 Modularity Patterns And Practices For Developing Maintainable Applications Paul Bakker https://ebookbell.com/product/java-9-modularity-patterns-and- practices-for-developing-maintainable-applications-paul-bakker-5903132 Java 9 Modularity Patterns And Practices For Developing Maintainable Applications 1st Edition Sander Mak https://ebookbell.com/product/java-9-modularity-patterns-and- practices-for-developing-maintainable-applications-1st-edition-sander- mak-6718992 Java 9 Modularity Revealed Project Jigsaw And Scalable Java Applications Alexandru Jecan https://ebookbell.com/product/java-9-modularity-revealed-project- jigsaw-and-scalable-java-applications-alexandru-jecan-6724108
  • 5. Java 9 Recipes A Problem-Solution Approach Third Edition Josh Juneau
  • 6. Java 9 Recipes: A Problem-Solution Approach Josh Juneau Hinckley, Illinois, USA ISBN-13 (pbk): 978-1-4842-1975-1 ISBN-13 (electronic): 978-1-4842-1976-8 DOI 10.1007/978-1-4842-1976-8 Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at www.apress.com/9781484219751. For more detailed information, please visit http://www.apress.com/source-code. Library of Congress Control Number: 2017943502 Copyright © 2017 by Josh Juneau
  • 7. Contents at a Glance About the Author�������������������������������������������������������������������������������������������������� xliii About the Technical Reviewer��������������������������������������������������������������������������������xlv Acknowledgments������������������������������������������������������������������������������������������������xlvii Introduction�����������������������������������������������������������������������������������������������������������xlix ■ ■Chapter 1: Getting Started with Java 9����������������������������������������������������������������� 1 ■ ■Chapter 2: Java 9 Enhancements������������������������������������������������������������������������ 35 ■ ■Chapter 3: Strings����������������������������������������������������������������������������������������������� 47 ■ ■Chapter 4: Numbers and Dates���������������������������������������������������������������������������� 65 ■ ■Chapter 5: Object-Oriented Java������������������������������������������������������������������������� 99 ■ ■Chapter 6: Lambda Expressions������������������������������������������������������������������������ 137 ■ ■Chapter 7: Data Sources and Collections���������������������������������������������������������� 159 ■ ■Chapter 8: Input and Output������������������������������������������������������������������������������ 195 ■ ■Chapter 9: Exceptions and Logging������������������������������������������������������������������� 221 ■ ■Chapter 10: Concurrency����������������������������������������������������������������������������������� 239 ■ ■Chapter 11: Debugging and Unit Testing����������������������������������������������������������� 267 ■ ■Chapter 12: Unicode, Internationalization, and Currency Codes����������������������� 285 ■ ■Chapter 13: Working with Databases���������������������������������������������������������������� 305 ■ ■Chapter 14: JavaFX Fundamentals�������������������������������������������������������������������� 355 ■ ■Chapter 15: Graphics with JavaFX�������������������������������������������������������������������� 429 ■ ■Chapter 16: Media with JavaFX������������������������������������������������������������������������� 471
  • 8. ■ ■Chapter 17: Java Web Applications with JavaServer Faces������������������������������ 499 ■ ■Chapter 18: Nashorn and Scripting������������������������������������������������������������������� 529 ■ ■Chapter 19: E-mail��������������������������������������������������������������������������������������������� 553 ■ ■Chapter 20: JSON and XML Processing������������������������������������������������������������� 563 ■ ■Chapter 21: Networking������������������������������������������������������������������������������������ 585 ■ ■Chapter 22: Java Modularity����������������������������������������������������������������������������� 605 Index��������������������������������������������������������������������������������������������������������������������� 615
  • 9. Introduction The Java programming language was introduced in 1995 by Sun Microsystems. Derived from languages such as C and C++, Java was designed to be more intuitive and easier to use than older languages, specifically due to its simplistic object model and automated facilities such as memory management. At the time, Java drew the interest of developers because of its object-oriented, concurrent architecture; its excellent security and scalability; and because applications developed in the Java language could run on any operating system that contained a Java Virtual Machine (JVM). Since its inception, Java has been described as a language that allows developers to “write once, run everywhere” as code is compiled into class files that contain bytecode, and the resulting class files can run on any compliant JVM. This concept made Java an immediate success for desktop development, which later branched off into different technological solutions over the years, including development of web-based applications and rich Internet applications (RIAs). Today, Java is deployed on a broad range of devices, including mobile phones, printers, medical devices, Blu-ray players, and so on. The Java platform consists of a hierarchy of components, starting with the Java Development Kit (JDK), which is composed of the Java Runtime Environment (JRE), the Java programming language, and platform tools that are necessary to develop and run Java applications. The JRE contains the JVM, plus the Java application programming interfaces (APIs) and libraries that assist in the development of Java applications. The JVM is the base upon which compiled Java class files run and is responsible for interpreting compiled Java classes and executing the code. Every operating system that is capable of running Java code has its own version of the JVM. To that end, the JRE must be installed on any system that will be running local Java desktop or stand-alone Java applications. Oracle provides JRE implementations for most of the major operating systems. Each operating system can have its own flavor of the JRE. For instance, mobile devices can run a scaled-down version of the full JRE that is optimized to run Java Mobile Edition (ME) and Java SE embedded applications. The Java platform APIs and libraries are a collection of predefined classes that are used by all Java applications. Any application that runs on the JVM makes uses the Java platform APIs and libraries. This allows applications to use the functionality that has been predefined and loaded into the JVM and leaves developers with more time to worry about the details of their specific application. The classes that comprise the Java platform APIs and libraries allow Java applications to use one set of classes in order to communicate with the underlying operating system. As such, the Java platform takes care of interpreting the set of instructions provided by a Java application into operating system commands that are required for the machine on which the application is being executed. This creates a facade for Java developers to write code against so that they can develop applications that can be written once and run on every machine that contains a relevant JVM. The JVM and the Java platform APIs and libraries play key roles in the life cycle of every Java application. Entire books have been written to explore the platform and JVM. This book focuses on the Java language itself, which is used to develop Java applications, although the JVM and Java platform APIs and libraries are referenced as needed. The Java language is a robust, secure, and modern object-oriented language that can be used to develop applications to run on the JVM. The Java programming language has been refined over several iterations and it becomes more powerful, secure, and modern with each new release. This book covers many features of the Java programming language from those that were introduced in Java 1.0 through those that made their way into the language in Java 9. In 2014, Oracle Corporation released Java 8, which was another milestone release for the Java ecosystem. Not only was Java already the most modern, statically
  • 10. ■ Introduction l typed, object-oriented language available for development, but Java 8 added important new enhancements to the language, such as lambda expressions, streams processing, and default methods. JavaFX 8 was also released at the same time, advancing desktop Java applications more than ever. JavaFX 8 can be used for developing rich desktop and Internet applications using the Java language, or any other language that runs on the JVM. It provides a rich set of graphical and media user interfaces to develop extraordinary visual applications. This release is another nice update to the JavaFX platform, adding in features such as the Swing node and the Print API. In 2017, Java 9 is released, enhancing the platform with features such as modularity, an updated Process API, and jShell. This book covers the fundamentals of Java development, such as installing the JDK, writing classes, and running applications. It delves into essential topics such as the development of object-oriented constructs, exception handling, unit testing, and localization. The book also provides solutions for desktop application development using the JavaFX, and some web-based and database solutions. It covers JavaFX in depth and is an essential guide for developers beginning to use JavaFX 8+. This book can be used as a guide for solving problems that ordinary Java developers may encounter at some point. A broad range of topics is discussed, and the solutions to the problems that are covered in this book are concise and to the point. If you are a novice Java developer, we hope that this book will help you get started on your journey to working with one of the most advanced and widely used programming languages available today. For those of you who have used the Java language for some time, we hope that this book will provide you with updated material that is new to Java 9, JavaFX, and even some Java web development so that you can further refine your Java development skills. I ensure that advanced Java application developers will also learn a thing or two regarding the new features of the language and perhaps even stumble upon some techniques that were not used in the past. Whatever your skill level, this book is good to have close at hand as a reference for solutions to those problems that you encounter in your daily programming. Who This Book Is For This book is intended for all those who are interested in learning the Java programming language and/or already know the language but would like some information regarding the new features included in Java SE 9 and JavaFX. Those who have not yet programmed in the Java language can read this book, and it will allow them to start from scratch to get up and running quickly. Intermediate and advanced Java developers who are looking to update their arsenal with the latest features that Java SE 9 makes available to them can also read the book to quickly update and refresh their skill set. Java desktop programmers will find this book useful for its content on developing desktop applications using the JavaFX API. There is, of course, a myriad of other essential topics that will be useful to Java developers of any type. How This Book Is Structured This book is structured such that it does not have to be read from cover to cover. In fact, it is structured so that developers can chose which topics they wish to read about and jump right to them. Each recipe contains a problem to solve, one or more solutions to solve that problem, and a detailed explanation of how the solution works. Although some recipes may build upon concepts that have been discussed in other recipes, they contain the appropriate references so that the developer can find other related recipes that are beneficial to the solution. The book is designed to allow developers to get up and running quickly with a solution so that they can be home in time for dinner.
  • 11. 1 © Josh Juneau 2017 J. Juneau, Java 9 Recipes, DOI 10.1007/978-1-4842-1976-8_1 CHAPTER 1 Getting Started with Java 9 In this chapter we present a handful of recipes to help programmers who are new to the Java language, as well as those having experience in other languages, become accustomed to Java 9. You will learn to install Java, and also install an Integrated Development Environment (IDE) from which you’ll develop applications and experiment with the solutions provided in this book. You will learn basics of Java such as how to create a class and how to accept keyboard input. Documentation is often overlooked, but in this chapter you will quickly learn how to create great documentation for your Java code. ■ ■ Note Java 9 Recipes is not intended as a complete tutorial. Rather, it covers key concepts of the Java language. If you are truly new to Java, we recommend buying and reading one of the many Beginning Java books that are also published by Apress. 1-1. Creating a Development Environment Problem You want to install Java and experiment with the language. You’d also like a reasonable IDE to use with it. Solution Install Java Development Kit 9 (JDK. That gives you the language and a compiler. Then install the NetBeans IDE to provide a more productive working environment. Java Standard Edition (Java SE) is sufficient for most recipes in this book. To download the release, visit the following page on the Oracle Technology Network (OTN): http://www.oracle.com/technetwork/java/javase/overview/index.html Figure 1-1 shows the Downloads tab, and you can see the Java Platform download link and image prominently on the page. Next to that link is an image for the NetBeans IDE, which provides the option of downloading the JDK and NetBeans together. Choose the option that you prefer, download the release for your platform, and run the setup wizard to install. For the purposes of this book, I am using NetBeans IDE 8.2.
  • 12. Chapter 1 ■ Getting Started with Java 9 2 ■ ■ Note If you chose to only install the Java Platform (JDK) and not NetBeans, you can download NetBeans at a later time by visiting netbeans.org. How It Works The name Java™ is a trademark owned by Oracle Corporation. The language itself is open source, and its evolution is controlled by a process known as the Java Community Process (JCP). You can read more about that process at www.jcp.org. While the language is not owned per se by Oracle Corporation, its core development tends to be steered by that company. It is Oracle Corporation that runs the JCP, and that owns the jcp.org domain. There are many editions of Java, such as the Mobile Edition (ME) and the Enterprise Edition (EE). Java SE is the Standard Edition and represents the heart of the language. We’ve built the recipes in this book for Java SE programmers. Those interested in the development of embedded applications for devices such as Raspberry Pi may be interested in learning more about Java ME. Similarly, those interested in developing web applications and working with enterprise solutions may be interested in learning more about Java EE. ■ ■ Note Enterprise developers may want to buy and read a copy of Java EE 7 Recipes by Josh Juneau (Apress, 2013). There are several good websites that you can visit to learn more about Java and keep up to date with the latest on the platform. A good place to begin for all things Java is the following page on the OTN: http://www.oracle.com/technetwork/java/index.html Figure 1-1. Java SE Downloads page on the OTN
  • 13. Chapter 1 ■ Getting Started with Java 9 3 The wealth of resources available from this page can be overwhelming at first, but it’s worth your time to look around and get passingly familiar with the many links that are available. One of the links will be to Java SE, which takes you to the page shown earlier in Figure 1-1. It is from there that you can download Java SE and the NetBeans IDE. Also from there you have access to the official documentation, to community resources such as forums and newsletters, and to training resources designed to help you build knowledge in Java and become certified in the language. 1-2. Getting to “Hello, World” Problem You’ve installed Java SE 9 and the NetBeans IDE. Now you want to run a simple Java program to verify that your installation is working properly. Solution Begin by opening the NetBeans IDE. You should see a workspace resembling the one in Figure 1-2. You may see some projects in the left-hand pane if you’ve already been working on projects within the IDE. Figure 1-2. Opening the NetBeans IDE
  • 14. Chapter 1 ■ Getting Started with Java 9 4 Go to the File menu and select New Project. You’ll see the dialog in Figure 1-3. Choose the Java category, and then Java Application. Click Next to advance to the dialog shown in Figure 1-4. Figure 1-3. Creating a new Java SE project
  • 15. Chapter 1 ■ Getting Started with Java 9 5 Give your project a name. For the project related to this book, use the name Java9Recipes. Enter the project name into the Project Name text box at the top of the dialog in Figure 1-4. Then specify the name of your main class in the Create Main Class text box. Give the following name: org.java9recipes.chapter01.recipe1_02.HelloWorld Be sure to that you’ve entered the project name and class name just as we provide them here, because the code to follow depends upon your doing so. Make sure the “Project Name” text box specifies Java9Recipes. Make sure the “Create Main Class” text box specifies org.java9recipes.chapter01. recipe1_02.HelloWorld. ■ ■ Tip Pay attention to case; Java is case-sensitive. Press “Finish” to complete the wizard and create a skeleton project. You should now be looking at a Java source file. Skeleton code is generated for you, and your NetBeans IDE window should resemble the one in Figure 1-5. Figure 1-4. Naming the project
  • 16. Chapter 1 ■ Getting Started with Java 9 6 Place your cursor anywhere in the source code pane. Press Ctrl-A to select all the skeleton code. Then press Delete to get rid of it. Replace the deleted code with that from Listing 1-1. You can find the code in Listing 1-1 as part of our example download for the book. There are two files named HelloMessage.java and HelloWorld.java, which reside in a Java package named org.java9recipes.chapter01. recipe1_02. Note that all recipe solutions of substance throughout this book are in that example download. The first class, HelloMessage, is a container class that is used to hold a String-based message. Listing 1-1. A “Hello, World” Example package org.java9recipes.chapter01.recipe1_02; public class HelloMessage {     private String message = ;     public HelloMessage() {         this.message = Default Message;     }     public void setMessage (String m) {         this.message = m;     }     public String getMessage () {         return message.toUpperCase();     }    } The next class is named HelloWorld, and it initiates the program: public class HelloWorld {     /* The main method begins in this class */ Figure 1-5. Viewing the skeleton code generated by NetBeans
  • 17. Chapter 1 ■ Getting Started with Java 9 7     public static void main(String[] args) {         HelloMessage hm;              hm = new HelloMessage();         System.out.println(hm.getMessage());         hm.setMessage(Hello, World);         System.out.println(hm.getMessage());         } } Make sure you have pasted (or typed) the code from Listing 1-1. Compile and run the program, and you should see the following output: run: DEFAULT MESSAGE HELLO, WORLD BUILD SUCCESSFUL (total time: 1 second) This output will appear in a new pane named “Output” that is opened by NetBeans at the bottom of the IDE window. How It Works You can run almost all the solutions in this chapter using the same general technique shown in this recipe. We’ve been painstakingly detailed for that reason, showing the step-by-step screenshots just this one time. Packages The solution example begins by creating a Java package: package org.java9recipes.chapter01.recipe1_02; Packages are a way of grouping related classes together into a shared namespace. The idea is to achieve universal uniqueness by working your way down your organization’s domain name in reverse order. It is also customary to write package names in all lowercase. NetBeans will create a directory structure to imitate your package path. In this case, NetBeans created the following directory path: C:UsersJonathanGennickDocumentsNetBeansProjects Java9Recipessrcorgjava9recipeschapter01recipe1_02 Following are some things to notice about this path: • The front part is C:Users...NetBeansProjects. NetBeans creates all projects under a NetbeansProject directory unless you specify otherwise, which you can do from the dialog in Figure 1-4. Many developers specify shorter paths. • Next is the first occurrence of Java9Recipes. This occurrence corresponds to the project name you gave when you filled in the Project Name text box from Figure 1-4.
  • 18. Chapter 1 ■ Getting Started with Java 9 8 • Any source files you create go into the src directory. NetBeans creates other directories at this level. For example, NetBeans creates a build directory, and then underneath it is a classes subdirectory to hold your compiled class files. • Last are the directories mirroring the package path that you specify, in this case org java9recipeschapter01recipe1_02. When you compile your code, an identical structure is created under the buildclasses directory. Note that if using another IDE, you may see differences in the directories that are created. You do not need to explicitly create a package. If you do not create one, the Java compiler will create one for you, and give it a name that is hidden from you. We prefer to be explicit, and you should too. Being thoughtful and explicit about Java package names is de rigueur in the professional setting. Organization, as well as judiciously chosen naming conventions, is important when developing any significant application. JavaBeans-Style Classes Next in the solution example you see a class definition following the JavaBeans pattern. The definition of HelloMessage follows a pattern that you’ll encounter often in Java programming, and we include it for that reason. The class is a simple one, capable of holding a single, String field named message. Three methods are defined on the class: HelloMessage(). This method, also known as the constructor, is named the same as the class. In this case, it takes no arguments. It’s automatically invoked whenever you create a new object of the class. Note that this is known as a “no-arg” constructor because it is typed out within the class, and it takes no arguments. If you do not supply a constructor, the JVM will supply a default constructor (also takes no arguments) automatically. setMessage(String). This accessor method begins with the word set. It takes one parameter. It specifies the message to be returned by the corresponding get method. getMessage(). This accessor method returns the currently defined message. In our example, we choose to uppercase the message. ■ ■ Note Accessor methods are used in JavaBeans classes to access any privately declared class members. In this case, the private variable identified as message can be accessed using these methods. Accessor methods are more commonly referred to as “getters” and “setters.” Methods beginning with set and get are termed as setter and getter methods. The variable message is private to the class, which means you have no direct access to message from outside of the class. You’ll see the keyword this used in the class. It is a special keyword in Java used to reference the current object. Its use is redundant in Listing 1-1, but would be needed if any of the methods happened to create variables of their own that were also named message. It is common practice to make use of the “this” keyword to reference the class members from within the “getter” and “setter” methods. It is common in Java to mediate access to class variables through setter and getter methods like those in our example. Those methods represent a contract of sorts with other classes and your main program. Their benefit is that you can change the storage implementation of HelloMessage however you like. Other code that depends upon HelloMessage will continue to work properly so long as you maintain the external behavior of setMessage() and getMessage().
  • 19. Chapter 1 ■ Getting Started with Java 9 9 The Main Program The incantation public static void main(...) is used from within a public class to denote the entry point of a Java program. That declaration begins an executable method named main. You must specify one parameter that is an array of Strings, and typically that parameter is defined as String[] args. When you execute the currently selected class, NetBeans compiles the code to a set of binary files, and then transfers control to the main() method. NetBeans can also be configured to recompile on save, which would then cause the transfer of control to the main() method. That method, in turn, does the following: 1. Executes HelloMessage to create a variable named hm that is capable of holding an instance of the class HelloMessage. The variable hm is empty at this point. 2. Invokes new HelloMessage() to create an object of the class by that name. The no-argument constructor will be executed, and Default Message is now set as the greeting text. The new object is now stored in the variable hm. 3. Makes a call to System.out.println() to show that the object’s no-argument constructor has indeed executed as expected. The greeting DEFAULT MESSAGE is displayed in the “Output” pane. 4. Sets the message to be the traditional text Hello, World. 5. Makes another call to System.out.println() to output the new message that has just been set. Now you see the greeting HELLO, WORLD added to the “Output” pane. The pattern in the solution is common in Java programming. The main() method is where execution begins. Variables are defined, and objects are created using the new operator. Object variables are often set and retrieved using setter and getter methods. ■ ■ Tip Command-line apps are passé. System administrators and programmers sometimes write them as utilities, or to batch-process large amounts of data. But in the main, most of today’s applications are GUI applications. JavaFX is the way forward in writing standard desktop applications, and you can learn about it in Chapters 14 through 16. Recipe 14-1 provides what is essentially a “Hello,World” application in GUI form. JavaEE offers options for developing web-based applications for the Java Platform, and you can learn more about that in Chapter 17. 1-3. Configuring the CLASSPATH Problem You want to execute a Java program, or include an external Java library in the application you are executing. Solution Set the CLASSPATH variable equal to the directory location of the user-defined Java classes or Java Archive (JAR) files that you need to have access to for executing your application. Let’s say that you have a directory named JAVA_DEV located at the root of your OS drive, and all the files your applications needs to access are located in this directory. If this is the case, then you would execute a command such as the following: set CLASSPATH=C:JAVA_DEVsome-jar.jar
  • 20. Chapter 1 ■ Getting Started with Java 9 10 Or on Unix and Linux systems: export CLASSPATH=/JAVA_DEV/some-jar.jar Alternately, the javac command provides an option for specifying the location of resources that need to be loaded for an application. On all platforms, setting the CLASSPATH using this technique can be done via the -classpath option as follows: javac –classpath /JAVA_DEV/some-jar.jar Of course, on Microsoft Windows machines the file path will use the backslash () instead. ■ ■ Note The javac –cp option may be used, rather than specifying the –classpath option. How It Works Java implements the concept of a classpath. This is a directory search path that you can specify system-wide using the CLASSPATH environment variable. You can also specify the classpath for a specific invocation of the JVM via the java command’s -classpath option. (See Recipe 1-4 for an example.) ■ ■ Note The CLASSPATH is certainly going to remain important for many Java applications into the future. However, the new module system, introduced in Java 9, replaces the need to use the brittle CLASSPATH for those applications that are built to take advantage of modularization. See Chapter 22 for more information on Java Modularity. When executing Java programs, the JVM finds and loads classes as needed using the following search order: 1. The classes that are fundamental to the Java platform and are contained in the Java installation directory. 2. Any packages or JAR files that are located within the extension directory of the JDK. 3. Packages, classes, JAR files, and libraries that are loaded somewhere on the specified class path. You may need to access more than one directory or JAR file for an application. This could be the case if your dependencies are located in more than one location. To do so, simply use the delimiter for your operating system (; or :) as a separator between the locations specified by the CLASSPATH variable. Following is an example of specifying multiple JAR files in the CLASSPATH environment variable on Unix and Linux systems: export CLASSPATH=/JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar Alternatively, you can specify the class path via a command-line option: javac –classpath /JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar
  • 21. Chapter 1 ■ Getting Started with Java 9 11 When loading the resources for a Java application, the JVM loads all the classes and packages that are specified in the first location, followed by the second, and so on. This is important because the order of loading may make a difference in some instances. ■ ■ Note JAR files are used to package applications and Java libraries into a distributable format. If you have not packaged your application in that manner, you may simply specify the directory or directories in which your .class files reside. Sometimes you’ll want to include all JAR files within a specified directory. Do that by specifying the wildcard character (*) after the directory containing the files. For example: javac –classpath /JAVA_DEV/*:/JAVA_LIB/myjar.jar Specifying a wildcard will tell the JVM that it should be loading JAR files only. It will not load class files that are located in a directory specified with the wildcard character. You’ll need to specify a separate path entry for the same directory if you also want the class files. For example: javac –classpath /JAVA_DEV/*:/JAVA_DEV Subdirectories within the class path will not be searched. In order to load files that are contained within subdirectories, those subdirectories and/or files must be explicitly listed in the class path. However, Java packages that are equivalent to the subdirectory structure will be loaded. Therefore, any Java classes that reside within a Java package that is equivalent to the subdirectory structure will be loaded. ■ ■ Note It is a good idea to organize your code; it is also good to organize where you place your code on the computer. A good practice is to place all your Java projects within the same directory; it can become your workspace. Place all the Java libraries that are contained in JAR files into the same directory for easier management. 1-4. Organizing Code with Packages Problem Your application consists of a set of Java classes, interfaces, and other types. You want to organize these source files to make them easier to maintain and avoid potential class-naming conflicts. Solution Create Java packages and place source files within them much like a filing system. Java packages can be used to organize logical groups of source files within an application. Packages can help to organize code, reduce naming conflicts among different classes and other Java type files, and provide access control. To create a package, simply create a directory within the root of your application source folder and name it. Packages are usually nested within each other and conform to a standard naming convention. For the purposes of this
  • 22. Chapter 1 ■ Getting Started with Java 9 12 recipe, assume that the organization is named Juneau and that the organization makes widgets. To organize all the code for the widget application, create a group of nested packages conforming to the following directory structure: /org/juneau Any source files that are placed within a package must contain the package statement as the first line in the source. The package statement lists the name of the package in which the source file is contained. For instance, suppose that the main class for the widget application is named JuneauWidgets.java. To place this class into a package named org.juneau, physically move the source file into a directory named juneau, which resides within the org directory, which in turn resides within the root of the source folder for the application. The directory structure should look like the following: /org/juneau/JuneauWidgets.java The source for JuneauWidgets.java is as follows: package org.juneau; /** * The main class for the Juneau Widgets application. * @author juneau */ public class JuneauWidgets {     public static void main(String[] args){         System.out println(Welcome to my app!);     } } The first line in the source contains the package statement, which lists the name of the package that the source file is located within. The entire package path is listed in the statement, and the names in the path are separated by dots. ■ ■ Note A package statement must be the first statement listed within the Java source. However, there may be a comment or Javadoc comment written before the package statement. For more information on comments or Javadoc, please see Recipe 1-12. An application can consist of any number of packages. If the widget application contains a few classes that represent widget objects, they could be placed within the org.juneau.widget package. The application may have interfaces that can be used to interact with the widget objects. In this case, a package named org. juneau.interfaces may also exist to contain any such interfaces. How It Works Java packages are useful for organizing source files, controlling access to different classes, and ensuring that there are no naming conflicts. Packages are represented by a series of physical directories on a file system, and they can contain any number of Java source files. Each source file must contain a package statement
  • 23. Chapter 1 ■ Getting Started with Java 9 13 before any other statements in the file. This package statement lists the name of the package in which the source file resides. In the solution to this recipe, the source included the following package statement: package org.juneau; This package statement indicates that the source file resides within a directory named juneau, and that directory resides within another directory named org. Package-naming conventions can vary by company or organization. However, it is important that words are in all lowercase so they do not conflict with any Java class file names. Many companies or organizations will use the reverse of their domain name for package naming. However, if a domain name includes hyphens, underscores should be used instead. ■ ■ Note When a class resides within a Java package, it is no longer referenced by only the class name, but instead the package name is prepended to the class name, which is known as the fully qualified name. For instance, because the class that resides within the file JuneauWidgets.java is contained within the org. juneau package, the class is referenced using org.juneau.JuneauWidgets, not simply JuneauWidgets. An identically named class can reside within a different package (for instance, org.java9recipes. JuneauWidgets). Packages are very useful for establishing levels of security as well as organization. By default, different classes that reside within the same package have access to each other. If a source file resides within a different package than another file that it needs to use, an import statement must be declared at the top of the source file (underneath the package statement) to import that other file for use; otherwise, the fully qualified package.class name must be used within the code. Classes may be imported separately, as demonstrated in the following import statement: import org.juneau.JuneauWidgets; However, it is often likely that all classes and type files that reside within a package need to be used. A single import statement utilizing a wildcard character (*) can import all files within a named package as follows: import org.juneau.*; Although it is possible to import all files, it is not recommended unless absolutely necessary. As a matter of fact, it is considered a poor programming practice to include many import statements that use the wildcard. Instead, classes and type files should be imported individually. Organizing classes within packages can prove to be very helpful. Suppose that the widget application that was described in the solution to this recipe includes different Java classes for each different widget object. Each of the widget classes could be grouped into a single package named org.juneau.widgets. Similarly, each of the widgets could extend some Java type or interface. All such interfaces could be organized into a package named org.juneau.interfaces. Any substantial Java application will include packages. Any Java library or Application Programming Interface (API) that you use includes packages. When you import classes or types from those libraries and APIs, you are really importing packages.
  • 24. Chapter 1 ■ Getting Started with Java 9 14 1-5. Declaring Variables and Access Modifiers Problem You want to create some variables and manipulate data within your program. Furthermore, you wish to make some of the variables available to only the current class, whereas others should be available to all classes, or just the other classes within the current package. Solution Java implements eight primitive data types. There is also special support for the String class type. Listing 1-2 shows an example declaration of each. Draw from the example to declare the variables needed in your own application. Listing 1-2. Declarations for Primitive and String Types package org.java9recipes.chapter01.recipe1_05; public class DeclarationsExample {     public static void main (String[] args) {         boolean BooleanVal = true;  /* Default is false */         char charval = 'G';     /* Unicode UTF-16 */         charval = 'u0490';     /* Ukrainian letter Ghe(Ґ) */         byte byteval;       /*  8 bits, -127 to 127 */         short shortval;     /* 16 bits, -32,768 to 32,768 */         int intval;         /* 32 bits, -2147483648 to 2147483647 */         long longval;       /* 64 bits, -(2^64) to 2^64 - 1 */         float   floatval = 10.123456F; /* 32-bit IEEE 754 */         double doubleval = 10.12345678987654; /* 64-bit IEEE 754 */         String message = Darken the corner where you are!;         message = message.replace(Darken, Brighten);     } } ■ ■ Note If you’re curious about the Ukrainian letter in Listing 1-2, it is the Cyrillic letter Ghe with upturn. You can read about its history at: http://en.wikipedia.org/wiki/Ghe_with_upturn. You can find its code point value in the chart at http://www.unicode.org/charts/PDF/U0400.pdf. And the URL http://www.unicode. org/charts/ is a good place to start whenever you need to find the code point corresponding to a given character. Variables are subject to the concept of visibility. Those created in Listing 1-2 are visible from the main() method after they have been created, and they are deallocated when the main() method ends. They have no “life” beyond the main() method, and are not accessible from outside of main().
  • 25. Chapter 1 ■ Getting Started with Java 9 15 Variables created at the class level are a different story. Such variables can be termed as class fields or class members, as in fields or members of the class. Use of a member can be restricted to objects of the class in which it is declared, to the package in which it is declared, or it can be accessible from any class in any package. Listing 1-3 shows some of how to control visibility via the private and public keywords. Listing 1-3. Visibility and the Concept of Fields package org.java9recipes.chapter01.recipe1_05; class TestClass {     private long visibleOnlyInThisClass;     double visibleFromEntirePackage;     void setLong (long val) {         visibleOnlyInThisClass = val;     }     long getLong () {        return visibleOnlyInThisClass;     }   } public class VisibilityExample {                 public static void main(String[] args) {         TestClass tc = new TestClass();           tc.setLong(32768);         tc.visibleFromEntirePackage = 3.1415926535;         System.out.println(tc.getLong());         System.out.println(tc.visibleFromEntirePackage);     } } Output: 32768 3.1415926535 Members are typically bound to an object of a class. Each object of a class contains an instance of each member in the class. However, you can also define so-called static fields that occur just once, and with a single value that is shared by all instances of the given class. Listing 1-4 illustrates the difference. Listing 1-4. Static Fields package org.java9recipes.chapter01.recipe1_05; class StaticDemo {     public static boolean oneValueForAllObjects = false; } public class StaticFieldsExample {     public static void main (String[] args) {         StaticDemo sd1 = new StaticDemo();         StaticDemo sd2 = new StaticDemo();         System.out.println(sd1.oneValueForAllObjects);
  • 26. Chapter 1 ■ Getting Started with Java 9 16         System.out.println(sd2.oneValueForAllObjects);         sd1.oneValueForAllObjects = true;         System.out.println(sd1.oneValueForAllObjects);         System.out.println(sd2.oneValueForAllObjects);     } } Listing 1-4 produces the following output: false false true true The field oneValueForAllObjects was set to true only for the class instance named sd1. Yet it is true for instance sd2 also. This is because of the keyword static used in declaring that field. Static fields occur one time for all objects of their class. How It Works Listing 1-2 illustrates the basic format of a variable declaration: type variable; It’s common to initialize variables when declaring them, so you’ll often see: type variable = initialValue; Field declarations can be preceded by modifiers. For example: public static variable = initialValue; protected variable; private variable; It’s common to put the visibility modifier — public, protected, or private — first, but you are free to list the modifiers in any order you like. Be aware that there are additional modifiers that you will encounter and need to learn about as you get deeper into the language. By default, if no modifier has been specified, the class or member is made package-private, meaning that only other classes within the package have access to the member. If a class member is specified as protected, then it is also package-private, with the exception that any subclass of its class in another package also has access. The String type is special in Java. It’s really a class type, but syntactically you can treat it as a primitive type. Java automatically creates a String object whenever you enclose a String of characters within double quotes (...). You aren’t required to invoke a constructor, nor to specify the new keyword. Yet String is a class, and there are methods in that class that are available to you. One such method is the replace() method shown at the end of Listing 1-2. Strings are composed of characters. Java’s char type is a two-byte construct for storing a single character in Unicode-s UTF-16 encoding. You can generate literals of the char type in two ways: • If a character is easy to type, then enclose it within single quotes (e.g.: 'G'). • Otherwise, specify the four-digit UTF-16 code point value prefaced by u (e.g.: 'u0490').
  • 27. Chapter 1 ■ Getting Started with Java 9 17 Some Unicode code points require five digits. These cannot be represented in a single char value. See Chapter 12 if you need more information on Unicode and internationalization. Avoid using any of the primitive types for monetary values. Especially avoid either of the floating-point types for that purpose. Refer instead to Chapter 12 and its recipe on using the Java Money API to calculate monetary amounts (Recipe 12-10). BigDecimal can also be useful anytime you need accurate, fixed-decimal arithmetic. If you are new to Java, you may be unfamiliar with the String[] array notation, as demonstrated in the examples. Please see Chapter 7 for more information on arrays. It covers enumerations, arrays, and also generic data types. Also in that chapter are examples showing how to write iterative code to work with collections of values such as an array. 1-6. Compiling and Executing from the Command-Line or Terminal Interpreter Problem You aren’t able to install an IDE, or prefer to use a standard text editor for development. Moreover, you want to compile and execute your Java programs from the command line or terminal so that you have complete control over the environment. Solution Compile your programs using the javac command. Then execute them via the java command. Begin by making sure you have your JDK’s bin directory in your execution path. You might need to execute a command such as one of the following. Windows: setx path %path%;C:Program FilesJavajdk1.9.0bin OS X: export PATH=/Library/Java/JavaVirtualMachines/jdk1.9.0.jdk/Contents/Home/bin Then make sure your CLASSPATH environment variable includes the directory containing your Java code. The following is an example of setting the environment variable under Windows: set CLASSPATH=path-to-my-Java Now change your current working directory to be the one corresponding to your project. Recipe 1-2 had you create a project named Java9Recipes. Change to that project’s directory on a Windows system as follows: cd path-to-projectJava9Recipes Descend one level into the src subdirectory: cd src
  • 28. Chapter 1 ■ Getting Started with Java 9 18 From here, you can issue javac commands to compile any classes in your project. Prepend the appropriate package name as part of your path leading to each source file to be compiled. Be sure to include the .java extension after your file name. For example, issue the following command to compile the HelloWorld class from Recipe 1-2. Windows: javac orgjava9recipeschapter01recipe1_02HelloWorld.java OS X: javac org/java9recipes/chapter01/recipe1_02/HelloWorld.java Once the compilation is complete, you will have a .class file in the same directory as your .java file. For example, if you perform a directory listing, you should see four files: dir orgjava9recipeschapter01recipe1_02 HelloMessage.class HelloWorld.class HelloMessage.java HelloWorld.java Compilation produces two files. One is for HelloMessage, and the other is for the class named HelloWorld implementing the main() method. Execute the main() method by issuing the java command to invoke the Java Virtual Machine (JVM). Pass the fully qualified class name as a parameter to the command. Qualify the class name by prepending the package name, but this time use the same dot-notation as used in your source file. For example: java org.java9recipes.chapter1.recipe1_02.HelloWorld Do not specify .class at the end of the command. You are referencing HelloWorld now as a class name, and not as a file name. You should see the same output as from Recipe 1-2. ■ ■ Tip One must compile source code. Source code is kept in files with a .java suffix, so your operating system’s file and directory-path notation is appropriate. One executes a class. A class is an abstract concept in the language, so the language’s dot-notation becomes appropriate. Keep this distinction in mind to help yourself remember when to use which notation. How It Works The first two solution steps are housekeeping steps. You must have the Java compiler and the virtual machine in your execution path. It’s also necessary for any classes used by your program to be found somewhere along what is termed the classpath. One way to specify the class path is through the CLASSPATH environment variable. See Recipe 1-3 for more information on the classpath.
  • 29. Chapter 1 ■ Getting Started with Java 9 19 ■ ■ Note The Java Modularity system added a couple of options to the javac compiler. Please see Chapter 22 for more information. The command java with no c at the end is for executing compiled code. Pass as a parameter the qualified name of the class containing your main method. The JVM will interpret and execute the byte- code within that class, beginning from the main method. The JVM will search along the classpath for any additionally required classes such as HelloMessage. The compiler’s default behavior is to place each generated class file into the same directory as holds the corresponding source file. You can override that behavior through the -d option. For example: javac -d specify-different-location path-to-project Java9Recipessrcorgjava9recipeschapter1recipe1_02HelloWorld.java The -d option in this command designates a directory in our own environment as the target for holding generated class files. The command also specifies the full path and file name of the source file. Thus, the command can be executed with the same result regardless of the current working directory. ■ ■ Tip Configure your system so that your command-line environment has the execution path and classpath set correctly by default. The typical approach in Linux- or Unix-based operating systems is to put appropriate commands into your .profile or .bash_profile files. Under Windows you can specify environment variable defaults from the Control Panel window named System, by clicking the Advanced system settings link, and then the Environment Variables button. There may be times when you need to specify a custom class path for a specific execution of the JVM. You can do that through the -cp parameter, as follows: java -cp .;path-to-projectJava9Recipesbuildclassesorgjava9recipeschapter1 recipe1_02 org.java9recipes.chapter1.recipe1_02.HelloWorld This execution will search first in the current working directory (the leading dot in the classpath), and then under the specified package directory corresponding to where NetBeans would place the compiled classes. ■ ■ Note See Recipe 1-3 for more on configuring your classpath. 1-7. Developing Within the Interactive jShell Problem You wish to write Java code and have it interpreted immediately, so that you can test, prototype, and alter your code quickly, without the need to wait for compilation or the ceremony of writing an entire Java class to perform a trivial task.
  • 30. Chapter 1 ■ Getting Started with Java 9 20 Solution Make use of the interactive jShell, new in Java 9, by opening a command prompt or terminal, and executing the jshell utility. The jshell is located in your JDK home bin directory, just like the java and javac utilities. Assuming that the JDK/bin directory is in the CLASSPATH, the jShell can be invoked using as such: jshell |  Welcome to JShell -- Version 1.9.0 |  Type /help for help - Once the interpreter has been started, declarations can be defined for the lifetime of the jShell session, expressions and statements can be typed and executed immediately, and so on. The jShell also allows Java developers to write a shorthand version of the language by eliminating superfluous constructs such as semicolons. Listing 1-5 demonstrates some of the basic functionality that is provided by the jShell. Keep in mind that when you are using the interactive shell, if you at any time need assistance, you can type the /help command. Listing 1-5. Interactive jShell - System.out.println(Hello World) Hello World - 1 + 1 |  Expression value is: 2 |    assigned to temporary variable $1 of type int - System.out.println(Hello Java 9) Hello Java 9 - // working with classes - class Main {      // Main method      public static void main(String[] args) {          System.out.println(Classes within jShell);          int index = 0;          while(index = 10){              System.out.println(Looping: + index);              index++;          }      } } |  Added class Main - // List classes currently loaded in jShell - /classes |    class Main - // Execute Class - Main.main(null) Classes within jShell Looping: 0 Looping: 1
  • 31. Chapter 1 ■ Getting Started with Java 9 21 Looping: 2 Looping: 3 Looping: 4 Looping: 5 Looping: 6 Looping: 7 Looping: 8 Looping: 9 Looping: 10 - // Reset the state of the jshell - /r |  Resetting state. - /classes - // Using imports - import java.util.ArrayList - import java.util.List - ListString colors = new ArrayList(); |  Added variable colors of type ListString with initial value [] - colors.add(red) |  Expression value is: true |    assigned to temporary variable $4 of type boolean - colors.add(orange) |  Expression value is: true |    assigned to temporary variable $5 of type boolean - colors.add(yellow) |  Expression value is: true |    assigned to temporary variable $6 of type boolean - colors |  Variable colors of type ListString has value [red, orange, yellow] - // List the current jShell session variables - /v |    ListString colors = [red, orange, yellow] |    boolean $4 = true |    boolean $5 = true |    boolean $6 = true - // List the commands that have been executed - /list    1 : import java.util.ArrayList;    2 : import java.util.List;    3 : ListString colors = new ArrayList();    4 : colors.add(red)    5 : colors.add(orange)    6 : colors.add(yellow)    7 : colors
  • 32. Chapter 1 ■ Getting Started with Java 9 22 As mentioned previously, one of the boons to having an interactive shell is for prototyping code. In many cases, developers wish to prototype classes and objects. Listing 1-5 demonstrates how to type the code for a class into the jShell, along with some of the commands that can be useful while working with classes. When prototyping, it can oftentimes be helpful to copy code from your favorite editor and paste it into the jShell, then execute commands against it. How It Works The jShell provides a Read Evaluate Print Loop (REPL) environment for developers to type or paste in code “snippets” and have them executed immediately. Much like the REPL environments or other languages such as Groovy, Python, and JRuby, the jShell provides an excellent environment for prototyping code, and even for executing stored scripts of Java code on the fly. The jShell allows one to write abbreviated Java code, otherwise known as snippets. This can be beneficial as it allows one to focus on the logic, rather than the syntax. One of the most used shortcuts is the ability to leave semicolons off the end of a line. To facilitate rapid prototyping, variables can be declared outside of classes, expressions and methods can be typed on the fly outside of classes and interfaces, and expressions leave no side effects. Along with the ability to write code on the fly, the jShell provides a system that facilitates the addition, modification, and removal of code fragments within an active session or instance. An active session or instance of the jShell environment constitutes a single JShellState. An instance of the JShellState includes all previously defined variables, methods, classes, import statements, and so on, that have been made within that same jShell session. Once the jShell instance is terminated, the JShellState is ended, and therefore all declarations are lost. There are a number of helper commands that can be typed into the jShell to retrieve information regarding the current JShellState. The /classes command lists all of the classes that have been typed into the current JShellState. The /list command lists all of the statements, expressions, classes, methods, imports, and so on, that have been typed into the current JShellState. The /list command provides a line number next to each of the listings, which enables one to easily re-execute that line of code using typing / followed by the line number that you wish to re-execute. Therefore, if you wish to execute line number 2 again, you would type /2 to have that line executed again. Table 1-1 contains a complete listing of the commands available within jShell. Table 1-1. jShell Commands Command Description /l or /list Lists the sources typed into the current session. /e or /edit [name or id of source] Opens JShell Edit Pad. Optionally type the name or id of the source entry to edit. /d or /drop [name/id of source] Deletes or drops the source referenced by name or id. /s or /save [all|history] Saves sources that have been typed in the current session. /o or /open Opens a file of source within the jShell. /v or /vars Lists variables that have been declared in the current session along with their current values. /m or /methods Lists the methods that have been declared in the current session. /c or /classes Lists the classes that have been declared in the current session. /x or /exit Exits the current jShell session. /r or /reset Resets the JShellState for the current session. (continued)
  • 33. Chapter 1 ■ Getting Started with Java 9 23 If you type the /e command, a scratch pad editor known as “JShell Edit Pad” will open containing the sources that you’ve entered for the current JShellState, as shown in Figure 1-6. You can edit the sources within this pad and then click the “Accept” button to have those sources evaluated within jShell. Figure 1-6. JShell Edit Pad Command Description /f or /feedback [level] Initiates feedback- options include (off, concise, normal, verbose, default, or ?). /p or /prompt Toggles the display of the prompt within the shell. /cp or /classpath [path] Adds the typed path to the current CLASSPATH. /h or /history Lists the history of the active JShellState. /setstart [file] Reads and sets the startup definition file. /savestart [file] Saves the current session’s definitions to the designated startup file. /! Re-executes the last code snippet. /n Re-executes the nth code snippet. /-n Re-executes the nth previous code snippet. Table 1-1. (continued)
  • 34. Chapter 1 ■ Getting Started with Java 9 24 Other useful features of the jShell are that you can bring up the previously typed command by pressing the up arrow on your keyboard. The interactive shell also features tab-completion. If you begin typing a statement and then press the Tab key, either the statement will be autocompleted for you or a list of options for the characters currently typed will be displayed. It is also possible to set up a predefined list of imports so that each time a jShell session is started, those imports will occur automatically. The jShell provides an interactive environment that allows immediate feedback while typing code snippets. This can be beneficial for prototyping or learning the language. Other languages, such as Groovy, Python, and Scala, have similar REPL environments. Now that the jShell is available for Java, it opens the door for a more interactive environment for classroom use and increased developer prototyping productivity. ■ ■ Tip To learn more about the commands available within the jShell, simply type /help once the shell has opened. The help feature displays an extensive listing of the features available in the jShell. 1-8. Converting to and from a String Problem You have a value stored within a primitive data type, and you want to represent that value as a human- readable String. Or, you want to go in the other direction by converting a human-readable String into a primitive data type. Solution Follow one of the patterns from Listing 1-6. The listing shows conversion from a String to a double-precision floating-point value, and shows two methods for getting back to a String again. Listing 1-6. General Pattern for String Conversions package org.java9recipes.chapter01.recipe1_08; public class StringConversion {     public static void main (String[] args) {         double pi;         String strval;         pi = Double.parseDouble(3.14);         System.out.println(strval = String.valueOf(pi));         System.out.println(Double.toString(pi));     } } How It Works The solution illustrates some conversion patterns that work for all the primitive types. First, there is the conversion of a floating-point number from its human-readable representation into the IEEE 754 format used by the Java language for floating-point arithmetic: pi = Double.parseDouble(3.14);
  • 35. Chapter 1 ■ Getting Started with Java 9 25 Notice the pattern. You can replace Double with Float, or by Long, or by whatever other type is your target data type. Each primitive type has a corresponding wrapper class by the same name but with the initial letter uppercase. The primitive type here is double, and the corresponding wrapper is Double. The wrapper classes implement helper methods such as Double.parseDouble(), Long.parseLong(), Boolean. parseBoolean(), and so forth. These parse methods convert human-readable representations into values of the respective types. Going the other way, it is often easiest to invoke String.valueOf(). The String class implements this method, and it is overloaded for each of the primitive data types. Alternatively, the wrapper classes also implement toString() methods that you can invoke to convert values of the underlying type into their human-readable forms. It’s your own preference as to which approach to take. Conversions targeting the numeric types require some exception handling to be practical. You generally need to gracefully accommodate a case in which a character-string value is expected to be a valid numeric representation, but it’s not. Chapter 9 covers exception handling in detail, and the upcoming Recipe 1-10 provides a simple example to get you started. ■ ■ Caution Literals for the Boolean type are true and false. They are case-sensitive. Any value other than these two is silently interpreted as false when converting from a String using the Boolean parseBoolean() conversion method. 1-9. Passing Arguments via Command-Line Execution Problem You want to pass values into a Java application that is being invoked via the command line via the java utility. Solution Run the application using the java utility, and specify the arguments that you want to pass into it after the application name. If you’re passing more than one argument, each should be separated by a space. For example, suppose you want to pass the arguments to the class created in Listing 1-7. Listing 1-7. Example of Accessing Command-Line Arguments package org.java9recipes.chapter01.recipe1_09; public class PassingArguments {     public static void main(String[] args){         if(args.length 0){             System.out.println(Arguments that were passed to the program: );             for (String arg:args){                 System.out.println(arg);             }         } else {             System.out.println(No arguments passed to the program.);         }     } }
  • 36. Chapter 1 ■ Getting Started with Java 9 26 First, make sure to compile the program so that you have a .class file to execute. You can do that from within NetBeans by right-clicking the file and choosing the “Compile File” option from the context menu, or via the javac utility at the command line or terminal. Next, open a Command Prompt or terminal window and traverse into the buildclasses directory for your project. (See Recipe 1-6 for an extensive discussion of executing from the command line). For example: cd path-to-projectJava9Recipesbuildclasses Now issue a java command to execute the class, and type some arguments on the command line following the class name. The following example passes two arguments: java org.java9recipes.chapter01.recipe1_09.PassingArguments Upper Peninsula You should see the following output: Arguments that were passed to the program: Upper Penninsula Spaces separate arguments. Enclose Strings in double quotes when you want to pass an argument containing spaces or other special characters. For example: java org.java9recipes.chapter01.recipe1_09.PassingArguments Upper Peninsula The output now shows just one argument: Arguments that were passed to the program: Upper Penninsula The double quotes translate the String Upper Peninsula into a single argument. How It Works All Java classes that are executable from the command line or terminal contain a main() method. If you look at the signature for the main() method, you can see that it accepts a String[] argument. In other words, you can pass an array of String objects into the main() method. Command-line interpreters such as the Windows Command Prompt and the various Linux and Unix shells build an array of Strings out of your command-line arguments, and pass that array to the main() method on your behalf. The main() method in the example displays each argument that is passed. First, the length of the array named args is tested to see whether it is greater than zero. If it is, the method will loop through each of the arguments in the array by executing a for loop, displaying each argument along the way. If there are no arguments passed, the length of the args array will be zero, and a message indicating such will be printed. Otherwise, you see a different message followed by a list of arguments. Command-line interpreters recognize spaces and sometimes other characters as delimiters. It’s generally safe to pass numeric values as arguments delimited by spaces without bothering to enclose each value within quotes. However, you should get into the habit of enclosing character-string arguments in double quotes, as shown in the final solution example. Do that to eliminate any ambiguity over where each argument begins and ends.
  • 37. Chapter 1 ■ Getting Started with Java 9 27 ■ ■ Note All arguments are seen by Java as character Strings. If you pass numeric values as parameters, they enter Java as character Strings in human-readable form. You can convert them into their appropriate numeric types using the conversion methods shown in Recipe 1-8. 1-10. Executing a Script via the jShell Problem You wish to write a prototype or script and execute it via the jShell utility from the command line or terminal. Solution While the jShell is not intended to provide a new language syntax for Java development, it is possible to save source snippets for execution within the jShell into a file, and then pass the file to the jShell utility for execution. In this solution, we’ll save a simple snippet into a file named myScript.java, and execute it with the jShell utility. To get started, save the following source code into a file named myScript.java, and save it to your file system. System.out.println(Hello from jShell) /x Execute the script using the following syntax: jShell path-to-file/myScript.java Output: Hello from jShell How It Works Sometimes it can be beneficial to use a text editor or the JShell Edit Pad (see Recipe 1-7) to save sources that can be executed within the jShell environment. This increases the ability to rapidly prototype code, and it also facilitates the ability to develop scripts that can be executed time and time again. This can be useful for development of scheduled tasks or administrative tasks that can be executed by the JVM. As such, sources for the jShell can be stored into a file containing the extension of your choice, and then the file can be passed to the jShell for execution. In the solution, a simple String is printed as output, and then the jShell environment is exited. Notice that the /x command is placed on a separate line after the sources within the file. The /x command tells the jShell environment to exit upon completion. If exiting upon completion, any variables, method, classes, and so on, that are defined within the file are lost once the sources have run to completion and the jShell environment is closed. It is not recommended to write applications using the jShell environment for execution. In fact, GUI applications are out of scope for the jShell, and debuggers are also not supported. The environment is clearly intended for educational and prototyping purposes. However, some may find it handy to save snippets of code for execution via the jShell at a later time.
  • 38. Chapter 1 ■ Getting Started with Java 9 28 1-11. Accepting Input from the Keyboard Problem You are interested in writing a command-line or terminal application that will accept user input from the keyboard. Solution Make use of the java.io.BufferedReader and java.io.InputStreamReader classes to read keyboard entry and store it into local variables. Listing 1-8 shows a program that will keep prompting for input until you enter some characters that represent a valid value of type long. Listing 1-8. Keyboard Input and Exception Handling package org.java9recipes.chapter01.recipe1_11; import java.io.*; public class AcceptingInput {     public static void main(String[] args){         BufferedReader readIn = new BufferedReader(                 new InputStreamReader(System.in)         );         String numberAsString = ;         long numberAsLong = 0;         boolean numberIsValid = false;         do {             /* Ask the user for a number. */             System.out.println(Please enter a number: );             try {                 numberAsString = readIn.readLine();                 System.out.println(You entered + numberAsString);             } catch (IOException ex){                 System.out.println(ex);             }             /* Convert the number into binary form. */             try {                 numberAsLong = Long.parseLong(numberAsString);                 numberIsValid = true;             } catch (NumberFormatException nfe) {                 System.out.println (Not a number!);             }         } while (numberIsValid == false);       } }
  • 39. Chapter 1 ■ Getting Started with Java 9 29 Following is an example run of this program: Please enter a number: No You entered No Not a number! Please enter a number: Yes You entered Yes Not a number! Please enter a number: 42 You entered 42 BUILD SUCCESSFUL (total time: 11 seconds) The first two inputs did not represent valid values in the long data type. The third value was valid, and the run ended. How It Works Quite often our applications need to accept user input of some kind. Granted, most applications are not used from the command line or terminal nowadays, but having the ability to create an application that reads input from the command line or terminal helps to lay a good foundation, and may be useful in some applications or scripts. Terminal input can also be useful in developing administrative applications that you or a system administrator may use. Two helper classes were used in the solution to this recipe. They are java.io.BufferedReader and java.io.InputStreamReader. The early portion of the code that’s using those classes is especially important to understand: BufferedReader readIn = new BufferedReader(         new InputStreamReader(System.in) ); The innermost object in this statement is System.in. It represents the keyboard. You do not need to declare System.in. Java’s runtime environment creates the object for you. It is simply available to be used. System.in provides access to raw bytes of data from the input device, which is the keyboard in our example. It is the job of the InputStreamReader class to take those bytes and convert them into characters in your current character set. System.in is passed to the InputStreamReader() constructor to create an InputStreamReader object. InputStreamReader knows about characters, but not about lines. It is the BufferedReader class’s job to detect line breaks in the input stream, and to enable you to conveniently read a line at a time. BufferedReader also aids efficiency by allowing physical reads from the input device to be done in different- size chunks than by which your application consumes the data. This aspect can make a difference when the input stream is a large file rather than the keyboard. Following is how the program in Listing 1-8 makes use of an instance (named readIn) of the BufferedReader class to read a line of input from the keyboard: numberAsString = readIn.readLine();
  • 40. Chapter 1 ■ Getting Started with Java 9 30 Executing this statement triggers the following sequence: 1. System.in returns a sequence of bytes. 2. InputStreamReader converts those bytes into characters. 3. BufferedReader breaks the character stream into lines of input. 4. readLine() returns one line of input to the application. I/O calls must be wrapped in try-catch blocks. These blocks are used to catch any exceptions that may occur. The try part in the example will fail in the event a conversion is unsuccessful. A failure prevents the numberIsValid flag from being set to true, which causes the do loop to make another iteration so that the user can try again at entering a valid value. To learn more about catching exceptions, please see Chapter 9. The following statement at the top of Listing 1-8 deserves some mention: import java.io.*; This statement makes available the classes and methods defined in the java.io package. These include InputStreamReader and BufferedReader. Also included is the IOException class used in the first try-catch block. 1-12. Documenting Your Code Problem You want to document some of your Java classes to assist in future maintenance. Solution Use Javadoc to place comments before any class, method, or field that you want to document. To begin such a comment, write the characters /**. Then begin each subsequent line with an asterisk (*). Lastly, close the comment with the characters */ on a line by themselves at the end. Listing 1-9 shows a method commented with Javadoc. Listing 1-9. Comments Made in Javadoc Form package org.java9recipes.chapter01.recipe1_12; import java.math.BigInteger; public class JavadocExample {     /**      * Accepts an unlimited number of values and      * returns the sum.      *      * @param nums Must be an array of BigInteger values.      * @return Sum of all numbers in the array.      */
  • 41. Chapter 1 ■ Getting Started with Java 9 31      public static BigInteger addNumbers(BigInteger[] nums) {          BigInteger result = new BigInteger(0);          for (BigInteger num:nums){              result = result.add(num);          }          return result;      }     /**      * Test the addNumbers method.      * @param args not used      */      public static void main (String[] args) {          BigInteger[] someValues = {BigInteger.TEN, BigInteger.ONE};          System.out.println(addNumbers(someValues));      } } Comments can be added to the beginning of classes and fields in the same way. The comments are helpful to you and other programmers maintaining the code, and their specific format enables easy generation of an HTML reference to your code. Generate the HTML reference by invoking the tool named Javadoc. This is a command-line tool that parses a named Java source file and formulates HTML documentation based upon the defined class elements and Javadoc comments. For example: javadoc JavadocExample.java This command will produce several HTML files containing the documentation for the class, methods, and fields. If no Javadoc comments exist within the source, some default documentation will still be produced. To view the documentation, load the following file into your browser: index.html The file will be in the same directory as the class or package that you are documenting. There will also be an index-all.html file giving a strict alphabetical listing of documented entities. Keep in mind that the same rules apply when using the Javadoc tool as when using javac. You must reside within the same directory as the source file, or prepend the name of the file with the path to where the file is located. How It Works Generating documentation for applications from scratch can be quite tedious. Maintaining documentation can be even more troublesome. The JDK comes packaged with an extensive system for documentation known as Javadoc. Placing some special comments throughout your code source and running a simple command-line tool makes it easy to generate useful documentation and keep it current. Moreover, even if some of the classes, methods, or fields in an application are not commented specifically for the Javadoc utility, default documentation will still be produced for such elements.
  • 42. Chapter 1 ■ Getting Started with Java 9 32 Formatting the Documentation To create a Javadoc comment, begin with the characters /**. Although optional since Java 1.4, a common practice is to include an asterisk as the first character of every subsequent line within the comment. Another good practice is to indent the comment so that it aligns with the code that is being documented. Lastly, close the comment with the characters */. Javadoc comments should begin with a short description of the class or method. Fields are rarely commented using Javadoc, unless they are declared public static final (constants), in which case it is a good idea to supply a comment. A comment can be several lines in length, and can even contain more than one paragraph. If you want to break comments into paragraphs, then separate those paragraphs using the p tag. Comments can include several tags that indicate various details regarding the method or class that is being commented. Javadoc tags begin with an ampersand (@), and some of the common tags are as follows: @param: Name and description of a parameter @return: What is returned from the method @see: Reference to another piece of code You may also include inline links within Javadoc to reference URLs. To include an inline link, use the tag {@link My Link}, where link is the actual URL that you want to point at and My Link is the text that you want to have appear. There are also many other tags that can be used within Javadoc comments, including {@literal}, {@code}, {@value org}, and many others. For a complete listing, see the Javadoc reference on the OTN website. Executing the Tool The Javadoc tool can also be run against entire packages or source. Simply pass a package name to the Javadoc tool rather than individual source file names. For instance, if an application includes a package named org.juneau.beans, all source files within that package can be documented by running the tool as follows: javadoc org.juneau.beans To generate Javadoc for more than one package at a time, separate the package names with spaces as follows: javadoc org.juneau.beans org.juneau.entity Another option is to specify the path to the source files using the –sourcepath flag. For example: javadoc –sourcepath /java/src By default, the Javadoc tool will generate HTML and place it into the same package as the code being documented. That result can become a cluttered nightmare if you like to have source files separate from documentation. You can instead set up a destination for the generated documentation by passing the –d flag to the Javadoc tool.
  • 43. Chapter 1 ■ Getting Started with Java 9 33 1-13. Reading Environment Variables Problem The application you are developing needs to make use of some environment variables. You want to read the values that have been set from the operating-system level. Solution Make use of the Java System class to retrieve any environment variable values. The System class has a method called getenv(), which accepts a String argument corresponding to the name of a system environment variable. The method will then return the value of the given variable. If no matching environment variable exists, a NULL value will be returned. Listing 1-10 provides an example. The class ReadOneEnvVariable accepts an environment variable name as a parameter, and displays the variable’s value that has been set at the operating-system level. Listing 1-10. Reading an Environment Variable’s Value package org.java9recipes.chapter1.recipe1_13; public class ReadOneEnvVariable {     public static void main(String[] args) {         if (args.length 0) {             String value = System.getenv(args[0]);             if (value != null) {                 System.out.println(args[0].toUpperCase() + = + value);             } else {                 System.out.println(No such environment variable exists);             }         } else {             System.out.println(No arguments passed);         }     } } If you are interested in retrieving the entire list of environment variables that is defined on a system, do not pass any arguments to the System.getenv() method. You’ll receive back an object of type Map having all the values. You can iterate through them as shown in Listing 1-11. Listing 1-11. Iterating Through a Map of Environment Variables package org.java9recipes.chapter1.recipe1_13; import java.util.Map; public class ReadAllEnvVariables {     public static void main(String[] args){         if(args.length 0){             String value = System.getenv(args[0]);         if (value != null) {             System.out.println(args[0].toUpperCase() + = + value);
  • 44. Chapter 1 ■ Getting Started with Java 9 34         } else {             System.out.println(No such environment variable exists);         }         } else {             MapString, String vars = System.getenv();             for(String var : vars.keySet()){                 System.out.println(var + = + vars.get(var));             }         }     } } How It Works The System class contains many different utilities that can aid in application development. One of those is the getenv() method, which will return a value for a given system environment variable. You can also return the values from all variables, in which case those values are stored in a map. A map is a collection of name/value pairs. Chapter 7 provides additional information about maps, including a recipe showing in detail how to iterate over them. The method invoked to obtain environment variable values in Listings 1-10 and 1-11 is the same. It’s been overloaded to handle both cases shown in the solution. Pass the name of a variable as a String if you want to obtain just that variable’s value. Pass no argument at all to get back the names and values of all variables that are currently set. Summary This chapter included recipes that allow you to get started working with Java quickly. It covered installation of the JDK, to installation and use of the NetBeans IDE. The chapter also covered basics such as declaring variables, compiling code, and documentation. The rest of this book dives deeper into each of the different areas of the Java language, covering a variety of topics from beginner to expert. Refer to this chapter for configuration specifics as you work through the examples in the rest of the book.
  • 45. 35 © Josh Juneau 2017 J. Juneau, Java 9 Recipes, DOI 10.1007/978-1-4842-1976-8_2 CHAPTER 2 Java 9 Enhancements Each release of the JDK brings forth new enhancements and capability to the Java platform. Each release also carries with it backward compatibility with previous releases. This book includes a number of recipes covering the new features for Java 9, and this chapter showcases a few of the top enhancements to whet your appetite. By no means is this chapter a complete listing of all Java 9 enhancements. Rather, it is a jump start to get you going on some of the hot new features of Java 9. 2-1. Avoiding Redundancy in Interface Code Problem You would like to implement two or more default methods within an interface that will contain very similar code. Rather than copying code into each of the different default methods and maintaining each default method separately, you’d like to encapsulate the similar code into its own method for reuse. Solution Make use of a private method in an interface to alleviate this issue. Java 9 provides the ability to include private methods within an interface. A private method is only available within that interface, and it cannot be used by any class that implements the interface. However, each default method implementation that is part of the interface can make use of the private method. The following interface includes two default methods and one private method. The private method encapsulates functionality that can then be used in each of the default method implementations. public interface Pool {     /**      * Calculate volume (gal) for a fixed depth square or rectangular pool.      */      public default double squareOrRectConstantDepth(double length, double width, double depth){         return volumeCalc(length, width, depth);     }     /**      * Calculate volume (gal) for a variable depth square or rectangular pool.      */
  • 46. Chapter 2 ■ Java 9 Enhancements 36     public default double squareOrRectVariableDepth(double length, double width,                                                     double shallowDepth, double middleDepth,                                                     double deepDepth){         double avgDepth = (shallowDepth + middleDepth + deepDepth) / 3;         return volumeCalc(length, width, avgDepth);     }     /**      * Standard square or rectangular volume calculation.      */     private double volumeCalc(double length, double width, double depth){         return length * width * depth * 7.5;     } } How It Works Prior to Java 8, it was not possible to include code implementation within a Java interface. An interface is a reference type in Java, similar to a class. However, its original intent only allowed abstract methods, constants, static methods, and nested types. Therefore, classes that implemented an interface must implement each of the abstract methods. In Java 8, that restriction was lifted, and it became possible to include method implementations in the form of default methods. A default method can contain an implementation in the interface, or its implementation could be overridden by an implementing class. Hence, the name default method, meaning that the default method implementation resides in the interface if one is not provided by the implementation class. Private methods were not allowed in interfaces. Situations have arisen by which multiple default methods within an interface may contain similar code. This code can now be encapsulated within a private method implementation within the interface. The private method implementation cannot be used outside of the interface. It can only be used by any default methods contained within the same interface. In the solution to this recipe, the volumeCalc() method returns the calculated volume of a square or rectangular swimming pool using a standard formula. Each of the default methods within the interface are able to utilize the volumeCalc() method to find the volume. However, the volumeCalc() method will not be available for use outside of the interface. This seems to be a controversial topic, as interfaces were originally intended for field and method declarations only, but it can also be argued that copying the same code throughout a number of default method implementations would be a bad practice. Take it as you will, this feature makes it easier to reuse code within an interface, thereby reducing the chance for errors and making maintenance much easier. 2-2. Creating Modules for Simplifying and Code Reuse Problem You are writing a utility library or a Java application, and you do not wish to rely upon the classpath to manage dependencies with other libraries. Furthermore, you wish to package your library such that it can easily be integrated into other projects. Solution Develop your library or application as a module. Creation of modules is quite easy. However, modules can themselves become quite complex. This example will cover the creation of a very simple module that does not depend upon any other modules. No other modules will depend upon the module either. Begin by
  • 47. Chapter 2 ■ Java 9 Enhancements 37 creating a new directory somewhere on your file system…in this case name it “recipe2-2.” Create a new folder named src within it, and then create a file named module-info.java, which is the module descriptor, within the src folder. In this file, list the module name as follows: module org.acme {} Next, create a folder named org.acme.wordcount within the src directory that was created previously (Figure 2-1). Next, create a folder named org within the org.acme.wordcount folder. Subsequently, create an acme folder within the org folder, followed by a wordcount folder within the acme folder. Figure 2-1. Module folder hierarchy Now, create the bulk of the module by adding a new file named WordCount.java inside of the wordcount folder. Place the following code within the WordCount.java file: package org.acme.wordcount; public class WordCount {     public static void main(String[] args) {         int counter = 0;         if (args.length 0){             for(String arg:args){                 System.out.println(Position + counter + : + arg.length());                 counter++;             }         }     }     } Make use of the javac utility to compile the module by using the command line or terminal and traversing inside of the src directory you created earlier. Issue the javac command, specifying the -d flag to list the folder into which the compiled code will be placed. List each of the source files to be compiled, including the module-info.java descriptor, separating each with a space. The following command compiles the sources that were developed in and places the result into a directory named mods/org.acme.wordcount. javac -d src/mods/org.acme.wordcount src/module-info.java src/org.acme.wordcount/org/acme/ wordcount/WordCount.java
  • 48. Chapter 2 ■ Java 9 Enhancements 38 Now that the code has been compiled, it is time to execute the module. Use the java executable, specifying the --module-path option, which is new in Java 9, to indicate the path of the module sources. The -m option is used to specify the Main class of the module. Traverse inside of the src directory and issue the following: java --module-path mods -m org.acme.wordcount/org.acme.wordcount.WordCount testing one two three This example passes the words “testing,” “one,” “two,” “three” to the module to be counted. The output should look as follows: Position 0: 7 Position 1: 3 Position 2: 3 Position 3: 5 How It Works Project Jigsaw brought modules into fruition for the Java platform, finally introducing a means to do away with the classpath of the old, and make use of a newer, more pluggable architecture. The Java 9 module system allows one to package self contained modules of code and make them versatile such that a module can be made to depend upon other modules, or on the other hand, other modules can be made to depend upon it. This modular dependency takes place of the old classpath system, although the classpath is still available for use to accommodate backward compatibility and also for cases where modularity makes little sense. Creation of a module consists of a module-info.java descriptor file. This file is used to indicate the package containing the module, as well as the dependency contracts that the module shares with other modules. Please see Chapter 22 for more details on the descriptor file. The self-contained application in this recipe resides within the org.acme.wordcount.WordCount.java file, and it can be compiled with javac, and executed with the java executable, as one would imagine. These two utilities have new options available to support modularity, and the recipe demonstrates the use of these new options for compiling and executing the module. For more details regarding module compilation and execution, see Recipe 22-2. 2-3. Easily Retrieving Information on OS Processes Problem You would like the ability to find information regarding operating system processes. Solution Make use of the updated Process API in Java 9. The new ProcessHandle interface allows one to easily obtain information regarding operating system processes. In the following code, all operating system processes are listed and printed to the command line. public static void listProcesses(){     ProcessHandle.allProcesses()             .forEach(System.out::println); }
  • 49. Chapter 2 ■ Java 9 Enhancements 39 However, this is not very helpful, as it simply lists the process number of each operating system process…which is not very useful. To obtain more detail on the process, we need to obtain the ProcessHandle and call upon its helper methods, which is quite easy to do. The following code will print much more information regarding each process, as it prints the ProcessHandle.Info itself. public static void detailListProcesses(){     ProcessHandle.allProcesses()             .forEach(h-System.out.println(formattedProcess(h))); } public static String formattedProcess(ProcessHandle handle){         long pid = handle.getPid();         boolean alive = handle.isAlive();         OptionalDuration cpuDuration = handle.info().totalCpuDuration();         OptionalString handleName = handle.info().command();         return pid + + alive + + handleName + :+ cpuDuration;      } Sample output may look as follows: 17584 true Optional[/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/ java]:Optional[PT0.250501S] 17581 true Optional[/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/ java]:Optional.empty 17576 true Optional.empty:Optional.empty 17575 true Optional.empty:Optional.empty 17574 true Optional.empty:Optional.empty 17364 true Optional[/System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata. framework/Versions/A/Support/mdworker]:Optional.empty 17247 true Optional[/Applications/Google Chrome.app/Contents/Versions/56.0.2924.87/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper]:Optional.empty If you wish to retrieve information pertaining to the user that is running the process, that is easy to do as well. public static void detailListProcessUsers(){     ProcessHandle.allProcesses()             .forEach(h-System.out.println(listOsUser(h))); } public static String listOsUser(ProcessHandle handle){     ProcessHandle.Info procInfo = handle.info();     return handle.getPid() + : +procInfo.user(); } Sample output using this technique may look as follows: 17584: Optional[Juneau] 17581: Optional[Juneau] 17576: Optional[_postfix] 17575: Optional[_postfix] 17574: Optional[root]
  • 50. Chapter 2 ■ Java 9 Enhancements 40 How It Works Prior to the release of Java 9, it was cumbersome to obtain information regarding operating system processes. We had to obtain process IDs using the ManagementFactory.getRuntimeMXBean() method and then parse the String that was returned. The ProcessHandle interface is introduced in Java 9, making the retrieval of operating system process information a first class citizen of the JDK. Table 2-1 shows the methods that can be called upon within ProcessInfo in order to retrieve the desired information. Table 2-1. ProcessHandle Interface Method Description allProcesses() Snapshot of all processes that are visible to the current process. children() Snapshot of the children of the current process. compareTo(ProcessHandle) Compare one ProcessHandle to another. current() Returns the ProcessHandle for the current process. descendants() Snapshot of all descendants of the current process. destroy() Requests the process to be killed. Returns a boolean to indicate result. destroyForcibly() Requests the process to be killed forcibly. Returns a boolean to indicate result. equals(Object) Returns a true if the object passed in is not null, and represents the same system process, otherwise returns a false. getPid() Returns the process ID for the process. hashCode() Returns hash code value for the process. info() Returns ProcessHandle.Info, which is a snapshot of information about the current process. isAlive() Returns a boolean to indicate whether the process is alive. of(long) Returns OptionalProcessHandle for an existing native process. onExit() Returns CompletableFutureProcessHandle for the termination of the process. The CompletableFuture can then be called upon to determine status. parent() Returns OptionalProcessHandle for the parent of the current process. supportsNormalTermination() Returns true if implementation of destroy() will terminate the process normally. 2-4. Handling Errors with Ease Problem You’d like to easily manage the closing of effectively final variables.
  • 51. Chapter 2 ■ Java 9 Enhancements 41 Solution The try-with-resources construct was introduced in Java 7, and it allows for easy management of resources. In Java 9, it became even easier as there is no need to effectively create a new variable for the sake of the construct. In the following code, the writeFile() method takes a BufferedWriter as an argument, and since it is passed into the method and ready to use, it is effectively final. This means that it can simply be listed in the try-with-resources, rather than creating a new variable. public static void main(String[] args) {     try {         writeFile(new BufferedWriter(                 new FileWriter(Easy TryWithResources)),                 This is easy in Java 9);     } catch (IOException ioe) {         System.out.println(ioe);     } } public static void writeFile(BufferedWriter writer, String text) {     try (writer) {         writer.write(text);     } catch (IOException ioe) {         System.out.println(ioe);     } } Prior to Java 9, the writeFile would have looked as follows: public static void writeFile(BufferedWriter writer, String text) {    try (BufferedWriter w = writer) {         w.write(text);     } catch (IOException ioe) {         System.out.println(ioe);     } } This code will create a new file named “Easy TryWithResources” and it will put the text “This is easy in Java 9” into the file. How It Works The try-with-resources construct has become even easier with Java 9. The try-with-resources construct was introduced in Java 8, which allows one to handle the opening and closing of resources very easily. If we have a resource, such as a database Connection or a BufferedStream, it is a good idea to manage wisely. In other words, open the resource, then use it accordingly, and finally close the resource when finished to ensure that there are no resource leaks. The try-with-resources construct allows one to open a resource within the try block and have it automatically cleaned up once the block completes. In the solution, the original way to handle resources is shown, followed by the new way in Java 9. It is now possible to simply begin making use of a resource within a try-with-resources construct if it is passed into a method as an argument or if it is a final field. This means that is no longer necessary to create a placeholder variable for the purposes of utilization within the try-with-resources. While this is not a major language change, it will certainly make handling resources a bit easier, and it certainly makes the try-with- resources block even easier to understand.
  • 52. Chapter 2 ■ Java 9 Enhancements 42 2-5. Filtering Data Before and After a Condition with Streams Problem You wish to utilize streams for effective manipulation of your collections. While doing so, you wish to filter those streams before and/or after a specified condition occurs. In the end, you want to retrieve all data within the collection before a given predicate condition is met. You also wish to retrieve all data within the collection that is placed after a given predicate condition is met. Solution Utilize the new Java 9 takeWhile() and dropWhile() constructs with your stream. Suppose we have the following collection of data, and we wish to retrieve all of the elements prior to the element containing the word “Java.” ListString myLangs = Arrays.asList(Jython is great,Groovy is awesome, Scala is functional, JRuby is productive,Java is streamlined,,Kotlin is interesting); To retrieve all elements prior to the element containing the String “Java” , we could use the takeWhile() construct, as follows: Stream.of(Jython is great,Groovy is awesome,Scala is functional,                 JRuby is productive,Java is streamlined,,Kotlin is interesting)                 .takeWhile(s - !s.contains(Java))                 .forEach(System.out::println); Let’s suppose that we wish to retrieve all elements that occur after the element containing the String “Java” . We could use the dropWhile() construct, as follows: Stream.of(Jython is great,Groovy is awesome,Scala is functional,                 JRuby is productive,Java is streamlined,,Kotlin is interesting)                 .dropWhile(s - !s.contains(Java))                 .forEach(System.out::println); How It Works Streams changed the way that we develop code and handle collections of data in Java. The original set of filters that were available for use with streams was fairly generous. However, in Java 8, even more options have been added, making it even easier to refine data with streams. The takeWhile() and dropWhile() constructs allow streams to be parsed, returning a new stream that contains all elements before the first one that fails the specified predicate condition, or returning a new stream containing all elements including and after the first element that fails a specified predicate, respectively. In the solution to this recipe, the list of Strings is parsed, printing each of the elements to the command line for the first pass. The takeWhile() construct is then applied to the same stream of Strings and the elements from the stream before the element that fails the specified condition will be printed to the command line. The takeWhile() accepts a predicate condition, which it then applies to each of the elements in the stream, and then only those elements that are iterated before the predicate condition is not matched will be returned. All elements that reside in the stream at and after the position where the condition is not met will not be returned.
  • 53. Chapter 2 ■ Java 9 Enhancements 43 The opposite result occurs when using the dropWhile() construct. In the solution, all stream elements will be ignored up until the first element upon which the specified condition is no longer met will be returned. Each subsequent element in the stream will also be returned. The takeWhile and dropWhile constructs are very similar to the filter, with the exception that only one failed condition will cause the remaining elements to be ignored or returned, respectively. 2-6. Developing a Concise HTTP Client Problem You wish to develop an HTTP client within a Java application. Solution Make use of the updated HTTP/2 client for Java 9. In the following example, the Apress website is parsed and returned via HTTP client code. In the following example, the Apress web page for US is returned as a String. HttpResponse r1; try {     r1 = HttpRequest.create(new URI(http://www.apress.com/us/))             .GET()             .response();     int responseCode = r1.statusCode();     if(responseCode == 200){         System.out.println(r1.body(asString()));     } } catch (URISyntaxException|IOException|InterruptedException ex) {     // Log error } The output will look something like the following (abbreviated for brevity): !DOCTYPE html !--[if lt IE 7] html lang=en class=no-js ie6 lt-ie9 lt-ie8 ![endif]-- !--[if IE 7] html lang=en class=no-js ie7 lt-ie9 lt-ie8 ![endif]-- !--[if IE 8] html lang=en class=no-js ie8 lt-ie9 ![endif]-- !--[if IE 9] html lang=en class=no-js ie9 ![endif]-- !--[if gt IE 9]!-- html lang=en class=no-js !--![endif]-- headmeta http-equiv=x-ua-compatible content=IE=edge script type=text/javascript src=//static.springer.com/spcom/js/vendor/googleapis/ajax/ libs/jquery/1.9.1/jquery.min.js/script script type=text/javascript src=//cdn.optimizely.com/js/8200882355.js/script script type=text/javascript id=angular-script src=//static.springer.com/spcom/js/ vendor/googleapis/ajax/libs/angularjs/1.2.17/angular.min.js/script script type=text/javascript id=script--1908162026 src=//static.springer.com/spcom/min/ prod.js?r=201702071421-9/script link rel=stylesheet type=text/css href=//static.springer.com/spcom/min/modern_sprcom- cms-frontend_apress.css?r=201702071421-9 /
  • 54. Chapter 2 ■ Java 9 Enhancements 44 !--[if (lt IE 9) (!IEMobile)]link rel=stylesheet type=text/css href=//static. springer.com/spcom/min/ielt9_sprcom-cms-frontend_apress.css?r=201702071421-9 media=screen /![endif]-- link rel=stylesheet type=text/css href=//static.springer.com/spcom/min/print. css?r=201702071421-9 media=print / link rel=stylesheet type=text/css href=/spcom/css/vendor/font-awesome.min. css?r=201702071421-9 / !--[if lt IE 9]script type=text/javascript id=ielt9js charset=utf-8 src=//static. springer.com/spcom/min/ielt9.js/script ■ ■ Note This is an excellent example to try out in the Java 9 jShell utility. To start the utility, open a command prompt or terminal and type jshell –add-modules java.httpclient to start the shell including the httpclient module. This assumes that the jshell executable utility resides within the PATH. How It Works The new javax.httpclient module has been added to Java 9, and it comprises of high level HTTP and WebSocket client APIs. The API provides synchronous and asynchronous implementations for the HTTP Client, and asynchronous implementations for WebSocket. The API resides within the java.net.http package. The HttpClient is a container for configuration information that is common to the HttpRequests type. An HttpClient is generated by initiating an HttpRequest.Builder, passing the URI for the request, and then calling upon the create() method. The create() method returns an immutable HttpClient. As seen in the solution to this recipe, the client can be used to perform a number of activities, both synchronously and asynchronously. Asynchronous requests will return a CompleteableFuture object for use. For more details regarding the HTTP and WebSocket clients, please refer to Recipe 21-7 and Recipe 21-8. 2-7. Redirecting Platform Logs Problem You wish to filter logs and redirect them to a specific file if they match the specified filtering criteria. Solution Utilize the Java 9 Unified Logging API to filter the logs and route accordingly. In the following excerpt from the command line or terminal, the java executable is invoked to execute a class named Recipe02_07. The -Xlog option is specified, passing gc=debug:file=gc.txt:none. This indicates that all log messages tagged with ‘gc’ using the ‘debug’ level should be written to the file gc.txt, and no decorations should be used. java -Xlog:gc=debug:file=gc.txt:none Recipe02_07 This will result in the creation of a file named gc.txt in the current directory, and all log messages pertaining to the specified –Xlog option will be written to it.
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. usurped by the Forerunners of Confusion and Anarchy, viz.: the Agitators. [The Army appointed a Committee of Adjutators on 14th May 1647.] My Commission as General bound me to act with [the co-operation of my] Council: but the arbitrary and unlimited power of this new Council would act without a General: and all that I could do, could not prevail against this stream; especially when the Parliament itself became divided, so that the pay was withheld from the Army, which heightened their distempers. Then followed, Free Quarter [in November 1647]; and that brought a general discontent through the whole nation: which gave these factious Agitators matter enough for the carrying on of their designs; viz., To raise their own fortunes by the ruin of others. But now, being much troubled to see things in this condition, I did rather desire to be a sufferer than to be a Commander: but, before I laid down my Commission, I thought it fit to consult with some friends rather than gratify my private sense and reason, which much desired it; especially having received it from a Public Authority, which might justly expect to have notice of it before I laid it down. Which was the cause of my continuing in the Army longer than I would have done (seeing I could not have my desire granted): which did indeed preserve the Parliament for some time, from those confusions and breakings, which afterwards Time and Confidence emboldened these men to. But now I shall descend to some particulars of their Agitation: At Nottingham was the first time that I took notice of it, by the soldiers' meetings to frame a Petition to the Parliament about their arrears [of pay]. The thing seemed just: but, not liking the way, I spake with some Officers that were principally engaged in it; and got it suppressed for that time. Which was but as the cutting off of Hydra's head, which soon sprang up again (though not so near the Head Quarters; but in more remote corners of the Army, which I could not so timely prevent) so that they presented it to the Parliament; which they were highly displeased with. And now falling into difference[s]; the consequence of which proved fatal not only to the King, but also destructive to one another. The one striving to uphold his authority: the other (who had a spirit of unsettlement) to preserve themselves from the ruin they feared. This (with a natural inclination to change) I believe created the thoughts of a New Government; which, in time, attained the name of a Common Wealth: though it never arrived to the perfection of it; being sometimes Democratical, sometimes Oligarchial, lastly Anarchial —as indeed all the ways attaining to it seemed nothing but a Confusion. For now the Officers of the Army were placed and displaced by the will of the new Agitators; who, with violence, so carried all things, as it was above my power to restrain it. This made me have recourse to my friends to get me a discharge of my
  • 57. Command; so as there was a consultation with several Members of Parliament, who met about it: but none would undertake to move it to the House, as affairs then stood. And they perceiving that such a Motion would be unpleasing to them: which was the answer I received from them. And further that I should satisfy myself: for it would be the Parliament's care to compose all things in as good order as might be most for the good and settlement of the Kingdom. But these hopes, though they something supported my spirit; yet could not they balance the grief and trouble I had, that I could not get my discharge. So that, if you find me carried on with this stream; I can truly say, It was by the violence of it, and no consent of mine. But the Army, having gotten this power and strength by correspondence with some in Parliament (who themselves did after find it [to their disadvantage] in the end) they [the Army] march nearer London [26th June 1647]: and, at Windsor [20th November 1647], after two days' debate in a Council of War, it was resolved to remove all out of the House [of Commons] whom they conceived to obstruct, as they called it, the Public Settlement. Upon which expedition in this march, I was vehemently pressed: but here I resolved to use a restrictive power, when I had not a persuasive one. So when the Lieutenant General [Oliver Cromwell] and others pressed me to sign orders for marching, I still delayed the doing of it [in November 1647]; as always dreading the consequences of breaking Parliament, and at a time when the Kingdom was falling into a new War: which was so near, that my delaying but three or four days giving out Orders, diverted this humour of the Army from being Statesmen to their more proper duty of soldiers. For, even then, Colonel Poyer declared [for the King] in Wales; great forces were raised with the Lord Goring in Kent; and Duke [of] Hamilton (almost at the same time) with a powerful Army of the Scots. All which set out work enough for that summer [of 1648]. This I write to shew how, by Providence, a few days' delay did prolong the Parliament more than a year from the violent breaches that afterwards happened to them. Here again might be mentioned the great and difficult businesses the Army went through that year [1648]: hoping, as well aiming, it would be a good service to the Kingdom. But, seeing the factious Party grew more insolent as success made them more powerful, I shall forbear to relate those Actions; which would, otherwise, have deserved a better remembrance than, in modesty, [it] were fit for me to record: and [I] will rather punish myself here, with the continuance of the Story of the Army's Irregularities. But one thing, of very great concernment in all after changes, should have been inserted before the mention of this Second War: but [it] will come in well enough in
  • 58. this place, without much interruption of this Discourse, viz.: THE KING'S REMOVAL FROM HOLMBY, the sad consequences whereof fill my heart with grief with the remembrance of it now; as it did then, with thoughts and care how to have prevented it. Being then at Saffron Walden in Essex, I had notice that Cornet Joyce (an arch- Agitator that quartered about Oxford) had [on 4th June 1647] seized on the King's person, and removed his Quarters: and [had] given such a check to the Commissioners of Parliament which were ordered to attend His Majesty, that they refused to act any further in their Commission; being so unwarrantably interrupted. But, as soon as I heard it, I immediately sent away two Regiments of Horse, commanded by Colonel Whalley to remove this force; and to set all things again in their due order and course. But before he reached Holmby [or Holdenby]; the King was advanced two or three miles [from thence] on his way towards Cambridge; attended by Joyce. Here Colonel Whalley acquainted the King, That he was sent by the General to let him know how much he was troubled at those great insolencies that had been committed so near his person: and as he had not the least knowledge of it before it was done, so he had omitted no time in seeking to remove the force; which he had orders from me to see done. And therefore [Colonel Whalley] desired that His Majesty would be pleased to return again to Holmby, where all things should again be settled in as much order and quietness as they were before. And also he [Colonel Whalley] desired the Commissioners to resume their Charge, as the Parliament had directed them: which he had in charge also to desire them to do, from the General. But the King refused to return; and the Commissioners refused also to act any more as Commissioners. Which Colonel Whalley still further urged, saying, He had an express command to see all things well settled again about His Majesty; which could not be but by his returning again to Holmby. Which the King said positively, He would not do. So Colonel Whalley pressed him no further: having indeed a special direction from me to use all tenderness and respect, as was due, towards His Majesty. So the King came that night, or the second [6th June 1647] to Sir John Cutt's house [at Childerley] near Cambridge: where, the next day, I waited on His Majesty. It being also my business to persuade his return to Holmby. But he was otherwise resolved. I pressed the Commissioners also to act again, according to the power that Parliament had given them: which they also refused to do. So having spent the whole day [7th June 1647] about this business; I returned to my Quarters.
  • 59. But before I took my leave of the King, he said to me, Sir, I have as great an Interest in the Army as you. By which I plainly saw the broken reed he leaned upon. These Agitators [or Adjutators], chameleon-like, could change into that colour which best served their ends; and so had brought the King into an opinion that the Army was for him: though [it was] never less for his safety and rights, than when it was theirs. And that it might appear what real trouble this act was to me; notwithstanding the Army was almost wholly infected with the humour of Agitation, I called for a Court of War, to proceed against Joyce for this high offence, and the breach of the Articles of War. But the Officers (whether for fear of the distempered soldiers; or rather, as I fear, from a secret allowance of what was done) made all my endeavours herein ineffectual: and now (no punishment being able to reach them) all affairs steer after this compass: The King and all his Party are in hopes. Those of the Parliament, and others who kept to their Covenant Interest, in fears. So as, for many months, Public Councils were turned into private Junto's. Which would have been less criminal, if it had ended in General Consent. But, on the contrary, it begat greater emulations and jealousies one of another. So that the Army would not entrust the King any longer with the liberty he had; nor would the Parliament suffer the King to undertake that which was properly their work to do, viz.: [the] Settling [of] the Kingdom with its just rights and liberties. And the Army were as jealous of the Parliament, that they [the Parliament] would not have care enough of their [the Army's] security. All things growing worse and worse made the King endeavour his own escape, as he did [11th-14th November 1647]; but out of a larger confinement at Hampton Court, to a straiter one in the Isle of Wight. Here the Parliament treated upon Propositions of Peace with the King. But, alas, the Envious One sowed tares that could not be rooted out, without plucking up the corn also. And here was the King, as the golden ball, tossed before the two great Parties; the Parliament, and the Army: [which] grew to a great contest, which must again have involved the kingdom in blood. But the Army, having the greater power, got the King again into their hands; notwithstanding all the means that could be used. The Treaty [? of Newport, ? October 1648] was scarcely ended, before the King was seized upon by the hands of the same person, Lieutenant Colonel Cobbett, who took him from Holmby [; and who now removed him, on 1st December 1648, from Carisbrooke Castle to Hurst Castle]. Soon after followed his Trial.
  • 60. But to prepare a way to this work [the Trial] this Agitating Council had thought first how to remove out of the Parliament all those who were likely to oppose them in that work; which they carried on with that secrecy as that I had not the least intimation of it, till it was done: as some Members of the House can witness, with whom I was met, at that very time, upon especial business, when that horrible attempt was made by Colonel Pride upon the Parliament [on 6th December 1648]. It was so secretly carried on that I should get no notice of it: because I always prevented those designs when I knew of them. But by this Purging of the House, as they called it, the Parliament was brought into such a consumptive and languishing condition as that it could never recover again that healthful Constitution which always kept the Kingdom in its strength and vigour. But now, this Three-fold Cord being cut by the sword, the Trial of the King was the easier for them to accomplish. My afflicted and troubled mind for it, and my earnest endeavours to prevent it, will, I hope, sufficiently testify my abhorrence of the fact. And what might they not now do to the lower shrubs, having thus cut down the cedar? For, after this, [the] Duke [of] Hamilton, [the] Earl of Holland, and Lord Capel, and others, were condemned to death. But here it is fit to say something for my own vindication about my Lord Capel, Sir Charles Lucas, and Sir George Lisle; who were prisoners at mercy upon the rendition of Colchester: seeing some have questioned the just performance of those Articles [of Surrender]. I (having laid siege to the town, and several assaults being made upon it) finding their forces within [to be] much more numerous than those I had without, forced me to take another course: blocking them up; and so, by cutting off all supplies, to bring them to a surrender. Which, after [a] four months' siege, they were necessitated to; and that upon mercy: they being between 3,000 and 4,000 men. Now by Delivering upon mercy is to be understood, that some are to suffer, and the rest to go free. So those forementioned persons only were to suffer; and all the rest freed. So immediately after our entrance into the town [on 26th August 1648], a Council of War being called; those persons were sentenced to die, the rest to be quit. Yet, on they being so resolved, I thought fit to manumit the Lord Capel, the Lord Norwich, c. over to the Parliament (being the Civil Judicature of the Kingdom, consisting then of Lords and Commons) as the most proper Judges of their cases: being considerable for estates and families. But Sir Charles Lucas and Sir George Lisle being mere Soldiers of Fortune; and falling into our hands by the chance of war, execution was done upon them. And in this
  • 61. distribution of Justice I did nothing but according to my Commission, and the trust reposed in me. But it may be objected that I went into the Court during the Trial. To this, I answer. It was upon the earnest entreaties of my Lord Capel's friends; who desired me to explain there, what I meant by Surrendering to mercy: otherwise I had not gone, being always unsatisfied with the Court. But for this I shall need to say no more: seeing I may as well be questioned for the Articles of Bristol, Oxford, Exeter; or [for] any other Action in the War, as for this. And now I have related the most remarkable things that might be alleged against me during the prosecution of the War. Yet one thing more requires that I should say something to it, before I conclude, viz.: Concerning Papers and Declarations of the Army that came out in my name and the Council of Officers. I must needs say. From the time they declared their Usurped Authority at Triplow Heath [10th June 1647], I never gave my free consent to anything they did: but (being then undischarged of my place) they set my hand [signature] by way of course, to all their Papers; whether I consented or not. And unto such failings all Authority may fall. As sometimes Kingly Authority may be abused to their, and the Kingdom's, prejudice; sometimes, under a Parliamentary Authority, much injury hath been done: so here, hath a General's Power been broken and crumbled into a Levelling Faction, to the great unsettlement of the Nation. Yet, even in this, I hope all impartial judges will interpret as a force and ravishment of a good name; rather than a voluntary consent whereby it might make me seem to become equally criminal. Though I must confess, if in a multitude of words, much more in a multitude of actions, there may be some transgressions: yet, I can as truly say, they were never designedly or wilfully committed by me. But now, when all the power was got into the Army, they cut up the root of Kingly Government. After this, were Engagements to relinquish the Title. Then [was] War declared against Scotland for assisting the King [Charles II.]: and several Leagues made with foreign Princes to confederate with their new Government, which was now a Common Wealth, against the Kingly Power. Seeing which, with grief and sorrow, though I had as much the love of the Army as ever; though I was with much importunity solicited by the remaining Parliament, the Lieutenant General [Oliver Cromwell], and other Officers and soldiers, to continue my Command; and though I might, so long as I acted their designs, attain to the height
  • 62. of power and other advantages I pleased (for so I understood from themselves): yet (by the mercy and goodness of GOD, ever valuing Loyalty and Conscience before this perishing felicity) I did, so long as I continued in the Army, oppose all those ways in their counsels; and, when I could do no more, I also declined their actions, though not their Commission I had from the Parliament, till the remaining part of it, took it from me [25th June 1650]. Thus I have given you, in short, the sum of the most considerable things that the World may censure me for, during this unhappy War. Yet, I hope, among many weaknesses and failings there shall not be found crimes of that magnitude [for me] to be counted amongst those who have done these things through ambition and dissimulation. Hoping also that GOD will, one day, clear this Action we undertook, so far as concerns his honour; and the integrity of such as faithfully served in it. For I cannot believe that such wonderful successes shall be given in vain. Though cunning and deceitful men must take shame to themselves; yet the purposes and determination of GOD shall have happy effects to his glory, and the comfort of his people.
  • 64. Thomas, third Lord Fairfax. A Short Memorial of the Northern Actions; during the War there, from the year 1642 till the year 1644. did not think to have taken up my pen any more, to have written on this subject: but that my silence seemed to accuse me of ingratitude to GOD for the many mercies and deliverances I have had; and of injuriousness to myself in losing the comfort of them, by suffering them to be buried in the grave of Oblivion in my lifetime. Wherefore I shall set down, as they come to my mind, such things wherein I have found the wonderful assistance of GOD to me in the time of the War I was in the North: though not in that methodical and polished manner as might have been done; being but intended only for my own satisfaction, and the help of my memory. As I said, in the First Part [p. 565], my father was called forth by the importunity of the country [Yorkshire], to join with them in the defence of themselves: and [was] confirmed by a Commission of the Parliament [by Vote on the 23rd August 1642. He however did not actually receive the Commission till the 3rd December following.] The first Action we had was at Bradford, where we had about 300 men. The Enemy, having about 700 or 800 and 2 pieces of ordnance, came thither to assault us [in October 1642]. We drew out close to the town to receive them. They had [the] advantage of [the] ground, the town being compassed with hills; which made us more exposed to their cannon shot, from which we received some hurt. Yet notwithstanding, our men defended the passages, which they [the Enemy] were to descend, so well that they got no ground of us. And now, the day being spent, they drew off; and returned back again to Leeds. A few days after, Captain Hotham, with 3 Troops of Horse and some Dragoons, came to me; and then we marched to Leeds. But the Enemy, having notice of it, quitt[ed] the town in haste; and fled to York. And that we might have more room, and be less burthensome to our friends; we presently advanced [in November 1642] to Tadcaster, 8 miles from York.
  • 65. Now we being increased to 1,000 men, it was thought fit, for securing of the West Riding, at least the greatest part of it, from whence our greatest supply came, to keep the Pass at Wetherby; whither my father sent me with about 300 Foot and 40 Horse. The Enemy's next design, from York, was to fall on my Quarters there; which was a place very open and easy for them to do: there being so many back ways to enter in; and friends enough to direct and acquaint them with all we did. About six of the clock in the morning [in November 1642], they set upon us with 800 Horse and Foot. The woods thereabouts favoured them so much as that our Scouts could get no notice of them; so as no alarm was given till they were ready to enter the town, which they might soon do for the Guards were all asleep in houses. For in the beginning of the War, men were as impatient of Duty as ignorant of it. Myself only was on horseback; going out, at the other end of the town, to Tadcaster: where my father lay. One came running to me, and told me, The Enemy was entering the town. I presently galloped to the Court of Guard [the Piquet], where I found not above four men at their arms; as I remember, two Foot Sergeants and two Pike men, [who] withstood with me when Sir Thomas Glenham, with about six or seven Commanders more, charged us: where, after a short but sharp encounter, in which Major Carr was slain, they retired. And in this time more of the Guard were gotten to their arms. But I must confess I know [of] no strength, but the powerful hand of GOD, that gave them this repulse. Afterward they made another attempt, in which Captain Atkinson was slain. And here again, there fell out another remarkable Providence. During this conflict, our Magazine was blown up: which struck such a terror in the Enemy, thinking we had cannon (which they were informed we had not), that they instantly retreated. And though I had but a few Horse; they pursued the Enemy some miles, and took many prisoners. We lost about eight or ten men, whereof seven were blown up with [the] powder: the Enemy, many more. [20] At this time [Henry Clifford] the Earl of Cumberland commanded the Forces in Yorkshire for the King. But (being of a peaceable nature; and by his amiable disposition having but few enemies, or rather because he was an enemy to few) he did not suit with their present condition and apprehension of fears. Therefore they sent to [William Cavendish] the Earl of Newcastle, who had an Army of 6,000 men, to desire his assistance: which he answered by a speedy march to York.
  • 66. Being now encouraged by this increase of force, they resolved to fall on Tadcaster. My father drew all his men thither. But by a Council of War the town was judged untenable; and that we should draw out to an advantageous piece of ground by the town. But before we could all march out; the Enemy advanced [on 7th December 1642] so fast that we were necessitated to leave some Foot in a slight Work above the bridge to secure our retreat. But the Enemy pressing still on us, forced us to draw back [return back], and maintain that ground. We had about 900 men. The Enemy above 4,000: who, in Brigades, drew up close to the Works, and stormed us. Our men reserved their shot till they were very near; which then they disposed to so good purpose as forced them to retire, and shelter themselves behind the hedges that were hard by. And here did the fight continue from 11 a clock at noon till 5 at night, with cannon and musket, without intermission. They had, once, possessed a house by the bridge; which would have cut us [off] from our reserves that were in the town: but Major General Gifford, with a commanded party, beat them out again; where many of the enemies were slain and taken prisoners. They attempted at another place; but were also repulsed by Captain Lister, who was there slain: which was a great loss, [he] being a discreet Gentleman. And now, it growing dark, the Enemy drew off into the fields hard by; with intention to assault us again the next day. They left that night about 200 dead and wounded upon the place. But our ammunition being all spent in this day's fight; we drew off that night, and marched to Selby: and the Enemy entered, the next day [8th December 1642], into the town [of Tadcaster]. And thus, by the mercy of GOD, were a few delivered from an Army who, in their thoughts, had swallowed us up. Now, the Earl of Newcastle lay between us and our friends in the West Riding; and so [was] equally destructive to us both. But, to give them encouragement and help, I was sent [on Friday, 9th December 1642], with about 200 Foot and 3 Troops of Horse and some arms, to Bradford. I was to go by Ferrybridge: our intelligence being that the Enemy was advanced yet no further than Sherburn. But when I was within a mile of the town [i.e. Ferrybridge]; we took some prisoners who told us That my Lord Newcastle laid at Pontefract, 800 men in Ferrybridge, and the rest of the Army in all the towns thereabouts.
  • 67. So as now, our advance, or retreat, seemed [to be] alike difficult. But, there being not much time to demur in, a retreat was resolved on back again to Selby. 300 or 400 of the Enemy's Horse shewed themselves in our rear, without making any attempt upon us; and so, through the goodness of GOD, we got safe thither. [Here, chronologically, comes in the Fight at Sherburn in Elmet, on Wednesday, 14th December 1642, described at page 584.] And, in three days after, [21] having better intelligence how they lay, with the same number as before, I marched in the night by several towns where they lay, and arrived, the next day, at Bradford: a town very untenable; but, for their good affections, deserving all we could hazard for them. Our first work there was to fortify ourselves; for we could not but expect strong opposition in it: seeing there lay at Leeds 1,500 of the Enemy, and 1,200 at Wakefield; neither above six or seven miles from us. They visited us every day with their Horse; for ours went not far from the town, being so unequal in number: yet they seldom returned without loss. Till, at length, our few men grew so bold; and theirs, so disheartened: as they durst not stir a mile out of their garrison. But while these daily skirmishes were among the Horse; I thought it necessary to strengthen ourselves with more Foot. So, summoning the country [i.e. the West Riding of Yorkshire], which now our Horse had given some liberty to come into us; I presently armed them with the arms we brought along with us: so that, in all, we were now about 800 Foot. But being too many to lie idle, and yet too few to be in continual duty; we resolved rather, through the assistance of GOD, to attempt them in their garrison than endure longer this trouble. So summoning the country in again; we made a body of about 1,200 or 1,300 men: with which we marched to Leeds, and drew them up [on Monday, 23rd January 1643] within [a] half cannon shot of their Works, in Battalia; and then sent in a Trumpet[er] with a Summons to deliver up the town to me, for the use of [the] King and Parliament. They presently returned this answer, That it was not civilly done to come so near before I sent the Summons; and that they would defend the town, the best they could, with their lives. So presently ordering the manner of the Storm, we all fell on at one time. The business was hotly disputed for almost two hours: but, after, the Enemy were beaten from their Works. The Barricadoes were soon forced open into the streets: where Horse and Foot resolutely entering, the soldiers cast down their arms, and rendered themselves prisoners. The Governor and some chief Officers swam the river and escaped. One Major Beaumont was drowned, as was thought. In all, there were about 40 or 50 slain; and [a] good store of ammunition [was] taken, which we had much want of.
  • 68. But the consequence of this Action was yet of more importance. For those that fled from Leeds and Wakefield, (for they also quitted that garrison) gave my Lord Newcastle such an alarm at Pontefract, where he lay; as he drew all his Army back again to York: leaving once more a free intercourse between my father [at Selby] and me, which he had so long time cut off. But, after a short time, the Earl of Newcastle returned again to the same Quarters [at Pontefract]; and we to our stricter duties. But, after some time, we found that our men must either have more room, or more action. [This Fight at Sherburn took place on the 14th December 1642; and should have been mentioned earlier in this Narrative.[22]] Therefore Captain Hotham and I took a resolution, early in the morning to beat up a Quarter [Encampment] of the Enemy that lay at [Church] Fenton. But they being gone, we marched towards Sherburn [in Elmet]; intending only to give them an alarm there. But they might see us, a mile or two, march over a plain common which lay by the Town; and therefore had sent about 20, or 30, Horse to guard a Pass near the town. I having the Van (For, at this time we [Fairfax and Hotham] commanded our Troops distinct one from another; both making 5 Troops of Horse and 2 of Dragoons), I told him, If he would second me, I would charge those Horse; and if they fled, I would pursue them so close[ly] as to get into the town with them. He promised to second me. I went to the head of my Troops, and presently charged them: who fled, and we pursued [them] close to the Barricado. But they got in, and shut it upon us; where my horse was shot at the breast. We so filled the lane; being strait [narrow] that we could not retreat without confusion, and danger of their falling in our rear. So we stood to it; and stormed the Work with pistol and sword. At the end of the Barricado, there was a straight passage for one single horse to go in. I entered there, and others followed one by one. Close at one side of the entrance stood a Troop of Horse: but so soon as eight or ten of us got in they fled. And by this time, the rest of our men had beaten them from their Barricado, and entered the town, which soon cleared the streets, and pursued those that fled. And now my horse, which was shot in the lane, fell down dead under me: but I was presently mounted again. They in the towns about having taken the alarm, now made us think of securing our retreat with the prisoners we had gotten: and some of them [were] very considerable; among whom was Major General Windham. But we scarce[ly] got into good order before General Goring came, with a good body of Horse, up to us: and as we marched on, he followed close in the rear, without [our] receiving any hurt; only my Trumpet[er] had his horse shot close by me. So we returned again to Selby. But though this could not free us wholly from a potent Enemy; yet we lay more quietly by them a good while after.
  • 69. In this recess of action, we had several treaties [negotiations] about prisoners. And this I mention the rather, for that Captain Hotham here began to discover his intention of leaving the Parliament's Service, by making conditions for himself with the Earl of Newcastle (though [it was] not discovered till a good while after): which had almost ruined my father, and the forces that were with him. For, being now denied help and succour from Hull and the East Riding; he was forced to forsake Selby, and retire to Leeds and those western parts where [I] myself was. But to make good this retreat, I was sent to, to bring what men I could to join with him at Sherburn. For Newcastle's forces lay so, as he might easily intercept us in our way to Leeds: which he had determined [to do], and to that end lay with his Army on Clifford Moor; having perfect intelligence of our march. But while my father, with 1,500 men ordnance and ammunition, continued [on 2nd April 1643] his way from Selby to Leeds; I, with those I brought to Sherburn, marched a little aside, between my Lord Newcastle's Army and ours. And to amuse [deceive] them the more, [I] made an attempt upon Tadcaster: whither they had 300 or 400 men; who presently quitted the town, and fled to York. Here we stayed three or four hours sleighting [destroying] the Works. This put Newcastle's Army to a stand, which was on their march to meet us: thinking that he was deceived in his intelligence; and that we had some other design upon York. He presently sent back the Lord Goring, with 20 Troops of Horse and Dragoons, to relieve Tadcaster. We were newly drawn off when they came. Goring pressed over the river to follow us. But seeing we were far unequal to him in Horse, for I had not above 3 Troops; and [having] to go over Bramham Moor, a large plain: I gave direction to the Foot to march away, while I stayed with the Horse to interrupt the Enemy's passage in those narrow lanes that lead up to the Moor. Here was much firing at one another. But, in regard of their great number, as they advanced we were forced to give way: yet had gained by it sufficient time for the Foot to be out of danger. But when we came up to the Moor again, I found them where I left them: which troubled me much, the Enemy being close upon us, and a great plain yet to go over. So [I] marched the foot in two Divisions, and the Horse in the rear. The Enemy followed, about two musket shot from us, in three good bodies: but yet made no attempt upon us. And thus we got well over the open campania. But having again gotten to some little enclosures, beyond which was another Moor, called Seacroft Moor [now called Whin Moor. It is about five miles from Leeds], much less than the first. Here our men thinking themselves more secure, were more careless in keeping order; and while their officers were getting them out of houses, where they sought for drink, [it] being an exceedingly hot day; the Enemy got, another way, as soon as we, on to the Moor. But we had almost passed this plain also.
  • 70. They [the Royalists] seeing us in some disorder, charged us both in Flank and Rear. The countrymen presently cast down their arms, and fled. The Foot soon after: which, for want of pikes, were not able to withstand their Horse. Some were slain; and many taken prisoners. Few of our Horse stood the charge. Some Officers, with me, made our retreat with much difficulty; in which Sir Henry Foulis had a slight hurt. My Cornet was taken prisoner. Yet [we] got to Leeds about two hours after my father, with those forces with him, was arrived safe thither. This was one of the greatest losses we ever received. Yet was it a great Providence that it was a part, and not the whole, [of the] Force which received this loss: it being the Enemy's intention to have fought us that day with their whole Army, which was, at least, 10,000 men; had not the Attempt at Tadcaster put a stand to them. And so concluded that day with this storm that fell on us. But now, being at Leeds, it was thought fit to possess some other place also: wherefore I was sent to Bradford, with 700 or 800 Foot and 3 Troops of Horse. These two towns being all the garrisons we had. At Wakefield, six miles off, lay 3,000 of the Enemy: but yet [we] had not much disturbance from them. Being most busied about releasing our prisoners that were taken at Seacroft Moor, most of them being countrymen [Yorkshire peasants]; whose wives and children were still importunate for their release: which was as earnestly endeavoured by us; but no conditions would be accepted. So their continual cries, and tears, and importunities compelled us to think of some way to redeem these men: so as we thought of attempting Wakefield; our intelligence being that the Enemy had not above 800 or 900 men in the town. I acquainted my father with our design: who approved of it; and sent [to Bradford] some men from Leeds; which enable us to draw out 1,100 Horse and Foot. So upon Whit-Sunday [21st May 1643], early in the morning, we came before the town. But they had notice of our coming, and had manned all their Works, and set about 800 Musketeers to line the hedges about the town: which made us now doubt our intelligence; which was too late. Notwithstanding, after a little consultation, we advanced, and soon beat them back into the town; which we stormed in three places. After two hours' dispute, the Foot forced open a Barricado, where I entered with my own Troop. Colonel Alured, and Captain Bright, followed with theirs. The street which we entered was full of their Foot: which we charged through, and routed; leaving them to the Foot which followed close behind us. And presently we were charged again with Horse led by General Goring: where, after a hot encounter, some were slain; and [he] himself taken prisoner by [the brother of] Colonel Alured. And I cannot but here acknowledge GOD's goodness to me this day: who being advanced a good way single [alone] before my men, having a Colonel and a Lieutenant Colonel, who had engaged themselves to be my prisoners, only with me;
  • 71. and many of the enemies between me and my men, I light[ed] on a Regiment of Foot standing in the Market Place. Thus encompassed, and thinking what to do; I espied a lane which I thought would lead me back to my men again. At the end of this lane, there was a Corps du Guard [Piquet] of the Enemy's, with 15 or 16 soldiers; who were then just quitting it, with a Serjeant leading them off: whom we met. Who, seeing their [two] Officers, came up to us; taking no notice of me. They asked them, What they would have them do? for they could keep the Work no longer; because the Roundheads, as they called them, came so fast upon them. But the Gentlemen, who had passed their words to me to be my true prisoners, said nothing. So, looking upon one another, I thought it not fit now to own them; as so much less to bid the rest to render themselves to me: so, being well mounted, and seeing a place in the Work where men used to go over, I rushed from them, seeing no other remedy, and made my horse leap over the Work. And so, by a good Providence, got to my men again: who, before I came, had, by the direction of Major General Gifford, brought up a piece of ordnance, and planted it in the Churchyard, against the body that stood in the Market Place; who presently rendered themselves. All our men being got into the town, the streets were cleared, [and] many prisoners taken. But the Horse got off almost entire. But this seemed the greater mercy when we saw our mistake: now finding 3,000 men in the town, [and] not expecting half the number. We brought away 1,400 prisoners, 80 Officers, 28 Colours; and [a] great store of ammunition, which we much wanted.[23] But seeing this was more a Miracle than a Victory; more the effect of GOD's divine power than human force; and more his Providence than the success of our prudence in making so hazardous an attempt: let the honour and praise of it be His only! After this, we exchanged our men that were prisoners, with these: and were freed, a good while; from any trouble or attempt from [the] Enemy. But then again it pleased GOD to mix water with our wine; and to bring us into a better condition by the brinks of ruin and destruction. Hitherto, through His mercy, we had held up near[ly] two years against a potent Army: but they finding us now almost tired, with continual Services; treacherously used by our friends; and in want of many things necessary for support and defence— the Earl of Newcastle marched with an Army of 10,000 or 12,000 men to besiege us; and resolved to sit down before Bradford, which was a very untenable place. My father drew all the forces he could spare out of the garrisons hither. But seeing it impossible to defend the town but by strength of men; and not [having] above ten or twelve days' provisions for so many as were necessary to keep it: we resolved [on 29th June 1643] the next morning, very early, with a party of 3,000
  • 72. men, to attempt his whole Army, as they lay in their Quarters, three miles off; hoping thereby, to put him into some distraction; which could not, by reason of the unequal numbers, be done any other way. For this end, my father appointed four of the clock next morning [30th June 1643] to begin the march. But Major General [John] Gifford, who had the ordering of the business, so delayed the execution of it that it was seven or eight before we began to move: and not without much suspicion of treachery in it; for when we came near the place we intended, the Enemy's whole Army was drawn up in Battalia. We were to go up a hill to them, which our Forlorn Hope [or Advanced Guard] gained by beating theirs into their Main Body; which was drawn up half a mile further, upon a plain called Adderton [the correct spelling is Adwalton] Moor. [It is also spelt Atherston and Atherton.] We, being all up the hill, drew into Battalia also. I commanded the Right Wing, which was about 1,000 Foot and 5 Troops of Horse; Major General [John] Gifford, the Left Wing, which was about the same number. My father commanded all in chief. We advanced through the enclosed grounds till we came to the Moor; beating the Foot that lay in them to their Main Body. 10 or 12 Troops of Horse charge us in the Right Wing [which was at the head of Warren's Lane]. We kept [to] the enclosures, placing our Musketeers in the hedges next the Moor; which was a good advantage to us, that had so few Horse. There was a gate, or open place, to the Moor: where five or six might enter abreast. Here they strove to enter: we, to defend. But, after some dispute, those that entered the pass found sharp entertainment; and those that were not yet entered, as hot welcome from the Musketeers, that flanked them in the hedges. All, in the end, were forced to retreat; with the loss of Colonel Howard, who commanded them. The Left Wing, at the same time, was engaged with the Enemy's Foot. Ours gained ground of them. The Horse came down again, and charged us: being about 13 or 14 Troops. We defended ourselves as before; but with much more difficulty, many having got in among us: but [they] were beat[en] off again, with some loss; and Colonel Herne, who commanded that party, was slain. We pursued them [back] to their cannon. And here I cannot omit a remarkable passage of Divine Justice. Whilst we were engaged in the fight with those Horse that entered the gate, four soldiers had stripped Colonel Herne naked; as he lay dead on the ground, [and] men still fighting round about him: and so dextrous were these villains, as they had done it, and mounted themselves again, before we had beaten them off. But after we had beaten them to their ordnance, as I said; and [were] now returning to our ground again; the Enemy discharged a piece of cannon in our rear. The bullet fell into Captain Copley's
  • 73. Troop, in which these four men were: two of whom were killed; and some hurt or mark remained on the rest, though dispersed into several Ranks of the Troop, which was [the] more remarkable. We had not yet Martial Law amongst us: which gave me a good occasion to reprove it; by shewing the soldiers the sinfulness of the act, and how GOD would punish when men wanted power to do it. This charge, and the resolution our soldiers shewed in the Left Wing, made the Enemy think of retreating. Orders were given for it; and some marched off the Field. Whilst they were in this wavering condition, one Colonel Skirton, a wild and desperate man, desired his General to let him charge [on our Left Wing] once more, with a Stand of Pikes. With which he brake in upon our men; and they not [being] relieved by our Reserves, ([which were] commanded by some ill-affected Officers; chiefly Major General Gifford, who did not his part as he ought to do), our men lost ground: which the Enemy seeing, pursued this advantage by bringing on fresh troops. Ours, being herewith discouraged, began to flee; and so [were] soon routed. The Horse also charged us again. We, not knowing what was done in the Left Wing; our men maintained their ground till a command came for us to retreat: having scarce any way now to do it; the Enemy being almost round about us, and our way to Bradford cut off. But there was a lane [Warren's Lane] in the field we were in, which led to Halifax: which, as a happy Providence, brought us off without any great loss; save of Captain Talbot and twelve more, which were slain in this last encounter. Of those [on the Left Wing] that fled, there were about 60 killed, and 300 taken prisoners. This business, having such ill success, our hopes of better could not be much: wanting all things that were necessary for defence, and [no] expectations of helps from any place. The Earl of Newcastle presently lay siege to the town [of Bradford]: but before he had surrounded it, I got in with those men I brought from Halifax. I found my father much troubled; having neither a Place of Strength to defend ourselves in, nor a garrison in Yorkshire to retreat to. For [Sir John Hotham the Elder,] the Governor of Hull had declared himself, If we were forced to retreat thither, that he would shut the gates on us. But, while he was musing on these sad thoughts, a messenger was sent from Hull to let him know, The townsmen had secured [taken prisoner] the Governor [on the morning of the 29th June 1643]; and if he had any occasion to make use of that place, for they were sensible of the danger he was in, he should be very readily and
  • 74. gladly received [there]. Which news was joyfully received, and acknowledged as a great mercy of GOD to us: yet was it not made use of till a further necessity compelled it. So my father, having ordered me to stay here [at Bradford] with 800 Foot and 60 Horse: he intruded [retired] that night [of 30th June 1643] for Leeds, to secure it. Now Newcastle, having spent three or four days in laying his Quarters about the town; they brought down their cannon: but needed to raise no batteries, for the hills, within half [a] musket shot, commanded all the town; which [cannon], now being planted in two places, shot furiously upon us. [They] making also Approaches; which made us spend very much [ammunition]. Our little store was not above five and twenty, or thirty, barrels of powder at the beginning of the siege: yet, notwithstanding, the Earl of Newcastle sent a Trumpet[er] to offer us Conditions; which I accepted so they were honourable for us to take, and safe for the inhabitants. Upon which, two Captains were sent to treat with him, and a Cessation [was agreed upon] during the time; but he continued working still, contrary to [the] agreement: whereupon I sent for the Commissioners again, suspecting a design of attempting something against us; but he returned them not till eleven a clock at night [of 1st July 1643], and then with a slight answer. Whilst they were delivering it to us, we heard great shooting of cannon and muskets. All ran presently to the Works, which the Enemy was storming. Here, for three- quarters of an hour, was very hot service: but, at length they retreated. They made a second attempt: but were also beaten off. After this, we had not above one barrel of powder left; and no Match. So I called the Officers together: where it was advised and resolved [evidently about 1 a.m. on the 2nd July 1643] to draw off presently, before it was day; and by forcing a way, which we must do (they having surrounded the town), [in order] to retreat to Leeds. Orders were despatched, and speedily put in execution. The Foot, commanded by Colonel Rogers, was sent out, through some narrow lanes; who were to beat up the Dragoons' Quarters [Encampment]; and so to go on to Leeds. [I] myself, with some other Officers, went with the Horse, which were not above 50, in an opener way. Here I must not forget to mention my Wife, who ran great hazards with us in this retreat as any others; and with as little expression of fear: not from any zeal or delight, I must needs say, in the War; but through a willing and patient suffering of this undesirable condition.
  • 75. But now I sent two or three Horsemen to discover what they could of the Enemy: which presently returned, and told us, There was a Guard of Horse close by us. Before I had gone forty paces, the day beginning to break, I saw them on the hill above us; being about 300 Horse. I, with some 12 more, charged them. Sir Henry Foulis, Major General Gifford, and myself, with three more [i.e., 6 out of 13] brake through. Captain Mudd was slain: and the rest of our Horse, being close by, the Enemy fell upon them, taking most of them prisoners; amongst whom my Wife was, the Officer behind whom she was [on horseback] being taken. I saw this disaster; but could give no relief. For after I was got through, I was in the Enemy's Rear alone; for those that had charged also through, went on to Leeds; thinking I had done so too. But being unwilling to leave my company: I stayed till I saw there was no more in my power to do; but to be made a prisoner with them. Then I retired to Leeds. The like disorder fell amongst the Foot that went the other way, by a mistake. For after they had marched a little way, the Van fell into the Dragoons' Quarters [Encampment], clearing the way. But through a cowardly fear of him that commanded those men who were in the Rear; [he] made them face about, and march again into the town [of Bradford]: where, the next day [2nd July 1643], they were all taken prisoners. Only 80, or thereabouts, of the Front, which got through, came to Leeds; all mounted on horses which they had taken from the Enemy: where I found them when I came thither; which was some joy to them, all concluding I was either slain or taken prisoner. I found all in great distraction here [i.e., at Leeds]. The Council of War was newly risen, where it was resolved to quit the town, and make our retreat to Hull; which was 60 miles off, and many garrisons of the Enemy on the way. Which, in two hours time was done: for we could expect no less than that the Enemy should presently send Horse to prevent it. For they had 50, or 60, Troops within three miles. But we got well to Selby; where there was a ferry: and, hard by, a garrison at Cawood. My father, being a mile before, with a few men getting over the ferry; word came to us that he was in danger to be taken. I hastened to him with about 40 Horse: the rest [of the Horse] coming on after in some disorder. He was newly got into the boat.
  • 76. The Enemy, with 3 Cornets of Horse, entering the town; I was drawn up in the Market Place, just before the street they came down. When they were almost half come into the Market Place, they turned on the right hand. With part of my Troop, I charged them in the Flanks; [and] so divided them. We had the chase of them down the long street that goes to Brayton. It happened, at the same time, [that] those men [which] I left behind, were coming up that street: [but] being in disorder, and under [the] discouragements of the misfortunes of many days before, [they] turned about, and gave way; not knowing that we were pursuing them in the rear. [That is, there were tearing along the Brayton road; (1) Fairfax's disordered Cavalry; then (2) the Royalist Cavalry; followed by (3) Fairfax with a part of his Troop.] At the end of this street, was a narrow lane which led to Cawood. The Enemy strove to pass away there; but [it] being strait [narrow], caused a sudden stop: where we were mingled one among another. Here I received a shot in the wrist of my arm, which made the bridle fall out of my hand: which [wound], being among the nerves and veins, suddenly let out such a quantity of blood as that I was ready to fall from my horse. So taking the reins in the other hand, wherein I had my sword; the Enemy minding nothing so much as how to get away: I drew myself out of the crowd, and came to our men that turned about; which were standing hard by. Seeing me ready to fall from my horse, they laid me on the ground: and [I] now, [being] almost senseless. My Chirurgeon came seasonably, and bound up the wound, [and] so stopped the bleeding. After a quarter of an hour's rest there, I got on horseback again. The other part of our Horse also beat the Enemy to Cawood back again, that way they first came to us. So, through the goodness of GOD, our passage here was made clear. Some went over the ferry, after my father. Myself, with others, went through the Levels [of the Fen Country, in North Lincolnshire; and south of the Humber] to Hull. But it proved a very troublesome and dangerous passage; having oft interruptions from the Enemy; sometimes in our front, sometimes in our rear. And now I had been at least twenty hours on horseback, after I was shot [at Selby], without any rest or refreshment: and as many hours before. [40 hours from 1 a.m. on the night of 2nd July 1643, when Fairfax decided to cut his way out of Bradford, would make it about 5 p.m. of the 3rd July 1643.]
  • 77. And, as a further addition to my affliction, my daughter [Mary, who afterwards married George Villiers, second Duke of Buckingham, see p. 611], not above five years old, being carried before her maid, endured all this retreat on horseback: but, Nature not [being] able to hold out any longer, [she] fell into frequent swoonings; and [was], in appearance, ready to expire her last [breath]. And having now passed the Trent [and therefore come into North Lincolnshire], and seeing a house not far off, I sent her, with her maid only, thither: with little hopes of seeing her any more alive; but intending, the next day, to send a ship from Hull for her. So I went on to Barton [upon Humber: nearly opposite Hull]; having sent before to have a ship ready against my coming thither. Here I lay down a little to rest; if it were possible to find any in a body so full of pain; and [in] a mind so full of anxiety and trouble. Though I must acknowledge it, as the infinite goodness of GOD, methought my spirits were nothing at all discouraged from doing still that which I thought to be my work and duty. But I had not laid [down] a quarter of an hour before the Enemy came close to the town [of Barton]. I had now not above 100 Horse with me. We went to the ship; where, under the covert of her ordnance, we got all our men and horses aboard. So passing [the] Humber, we arrived at Hull; our men faint and tired: [and I] myself having lost all, even to my shirt; for my clothes were made unfit to wear, with rents and the blood which was upon them. Considering which, in all humility and reverence, I may say, I was in Job's condition when he said, Naked came I out of my mother's womb, and naked shall I return thither. The Lord gave, and the Lord hath taken away. Blessed be the Name of the Lord. [Job i. 21.] But GOD, who is a GOD of Mercy and Consolation, doth not always leave us in distress. I having sent a ship, presently after I came into the town, for my daughter: she was brought, the next day [4th July 1643], to Hull; pretty well recovered of her long and tedious journey. And, not many days after, the Earl of Newcastle sent my Wife back again, in his coach, with some Horse to guard her: which generosity gained more than any reputation he could have gotten in detaining a Lady prisoner upon such terms. And many of our men, which were dispersed in this long retreat, came hither again to us. Our first business now, was to raise new forces: which, in a short time, were about 1,500 Foot and 700 Horse. The town [of Hull] being little; I was sent to Beverley with the Horse and 600 Foot.
  • 78. But my Lord [of] Newcastle, who now looked upon us as inconsiderable, was marched with his whole Army into Lincolnshire: only leaving some few garrisons at York and other few places. He took in Gainsborough and Lincoln; and intended [to take] Boston next, which was the Key of the Associated Countries [Counties]. For his Orders, which I have seen, were to go into Essex; and block up London on that side. But we, having laid a great while [from 4th July to 26th August 1643] still, were now strong enough in the Field for those forces that remained in the Country [Yorkshire]. So we sent out a good party to make an attempt upon Stamford Bridge, near York. But the Enemy, upon the alarm, fled thither [i.e. to York]; which put them all there in such a fear as they sent earnestly to desire him to return, or the Country [Yorkshire] would again be lost: for the Lord Fairfax had considerable forces. Upon which, he returned again into Yorkshire; and, not long after, came to besiege Hull. I, lying then at Beverley in the way of his march, finding that we were not able to maintain such an open place against an Army, desired Orders from my father to retire back to Hull. But the Committee there (having always more mind of raising money, than to take care of the Soldiers; yet these [Committee] Men had the greatest share in command at this time) would not let any Orders be given for our retreat; and [it were] unfit for us to return without [them]. The Enemy marcheth from York, with his whole Army, towards us. Retreat, we must not. Keep the town, we could not. So to make our retreat more honourable, and useful both; I drew out all the Horse and Dragoons toward the Enemy, and stood, drawn up by a wood side, all that night. The next morning [2nd September 1643], by day[time], our Scouts, and theirs, fired on one another. They march[ed] on with their whole body; which was about 4,000 Horse and 12,000 Foot. We stood till they were come very near [to] us. I then drew off (having given directions before for the Foot to march away toward Hull), thinking to make good the retreat with the Horse. The Enemy, with a good party, were upon our rear. The lane being but narrow, we made good shift with them till we got into Beverley, and shut the gates: which we had scarce time to do; they being so close upon us. But, in this business, we lost Major Layton, and not above 2 more. The Enemy, not knowing what forces we had in the town, stayed till the rest of the Army came up; which was about a mile behind. This gave our Foot some advantage in their retreat: it being 5 miles to Hull, on narrow banks [and] so fittest for our Foot. I sent the Horse by Cottingham, an opener road; who got well thither.
  • 79. But they [the Royalists] overtook the Foot: which, notwithstanding, made good their retreat till we got to a little bridge, 2 miles from Hull; where we made a stand. The Enemy following close, our men here gave them a good volley of shot; which made them draw back, and advance no further. So, leaving a small Guard at the bridge, we got safe to Hull. Thus not only for want of military skill in the Gentlemen of the Committee; but, to say no more, for want of good nature: we were exposed to this trouble and danger. My Lord of Newcastle now lay siege to Hull, but at a great distance. The sluices being open, drowned the land two miles about the town: yet upon a bank, which was the highway, he approached so near as to shoot cannon shot at random into the town; which were, for the most part, fiery bullets. But the diligence and care of the Governor (who caused every inhabitant to watch his own house; and wheresoever they saw these bullets fall, to be ready to quench them) prevented the danger. Our Horse was now useless: and many [horses] died every day; having nothing but salt water about the town. I was therefore sent with the Horse, over [the Humber] into Lincolnshire, to join with [Edward Montagu,] the Earl of Manchester's forces; which were then commanded by Major General [Oliver] Cromwell: who received us at our landing, with his troops. Sir John Henderson lay within three or four miles of this place with 5,000 men, to prevent our conjunction: but durst not attempt [it]. He marched three or four days near to us: but, for want of good intelligence, we did not know so much. For I altogether trusted to the care of our new friends, being a stranger in those parts: till one morning [9th October 1643] he set upon our Guards at Horncastle; which, being but newly raised in that Country [Lincolnshire], fled towards Lincoln, without giving any alarm to our Quarters, who lay dispersed and secure. But Sir John Henderson, marching slowly with his Army, gave the alarm to some of our Quarters; which was soon taken by the rest: but, with some disorder, before we could get into a considerable body. My Lord Willoughby with his Horse, and my Dragoons commanded by Colonel Morgan, brought up the Rear. After some skirmishes, we lodged that night all in the Field. And, next day [10th October 1643], the Earl of Manchester came to us with his Foot. The day following [11th October 1643], we advanced again towards the Enemy; and choosing a convenient ground to fight on, we drew up the Army there. The Enemy did so on the side of another hill close by, having a little plain betwixt us.
  • 80. Lieutenant General [Oliver] Cromwell had the Van [of Horse]; I, the Reserve [of Horse]: my Lord [of] Manchester all the Foot. After we had faced one another a little while; the Forlorn Hopes [Advanced Guards] began the fight. Presently the [Main] Bodies met in the plain: where the fight was hot for half an hour; but then we forced them to a rout. Above 200 killed, and 2000 taken prisoners. This was the issue of Horncastle Fight, or, as some call it, Winceby Fight. At the same instant, we heard great shooting of ordnance towards Hull: which was a sally my father made [out of the town] upon my Lord of Newcastle's Trenches; who drew out most part of his Army to relieve them. But our men charged so resolutely as they possessed themselves of the cannon; and so pursued their advantage as [they] put the enemy into a total rout. Upon which, he raised the Siege, and returned again to York. These two defeats together, the one falling heavy on the Horse, the other on the Foot, kept the Enemy all that Winter [of 1643-1644] from attempting anything. And we, after the taking of Lincoln, settled ourselves in Winter Quarters. But, in the coldest season of it, I was ordered by the Parliament to go and raise the Siege of Nantwich; which the Lord Byron, with the Irish Army, had reduced to great extremity. I was the most unfit of all the forces; being ever the worst paid; my men sickly, and almost naked for want of clothes. I desired the Parliament that they would be pleased to supply these wants: not to excuse myself, as some who had no will to stir, though well enough accommodated with all these; and a business of so much importance. But their answer was a positive direction to march; for it would admit of no delay: which indeed was as grievous to me as that injunction was to the Israelites, to make bricks without straw. But, foreseeing I should have such a return to my desires, I had, seeing the necessity of the business, upon my own credit got so much cloth as clothed 1,500 men: and [they were] all ready to march when these Orders came to me. So, the 29th of December [1643], we got forwards from Falkingham in Lincolnshire to Nantwich, with 1,800 Horse and 500 Dragoons; and a Power to call the Regiments [of Foot] of Lancashire and Cheshire to make up the body of the Army. But it was not a little trouble to me, when I came to Manchester, to find some of them 30, some 40 miles distant: besides the disaffection of some of their Colonels, who went as their peculiar [individual] safety or Interest swayed them. But, finding more readiness in the inferior Officers and common soldiers, I got up, in a few days, near[ly] 3,000 Foot. With this Army, we marched [from Manchester, on the 21st January 1644] to Nantwich; which was at the point of surrendering.
  • 81. When we were within two days' march, I had intelligence that the Lord Byron had drawn off his Siege; and intended to meet us in the Field. I put my men into the order I intended to fight [in]; and so continued my march till we came within 3 miles of the town. There, was a Pass kept with about 250 men. I sent Colonel Morgan, with his Dragoons, to beat them off: in which, his brother, who was his Lieutenant, was slain. The Major who commanded the other party, with some others, were taken prisoners. We marched on till we came within cannon shot of their Works, where half of their Army was drawn up. The river [Weaver], which runs through the town, being raised with the melting of the snow, hindered, as we were informed, those that lay on the other side of the town from joining with them. We called a Council [of War, on 25th January 1644] wherein it was debated, Whether we should attempt those in their Works [Entrenchments], being divided from the rest of the Army: or march into the town and relieve them; and, by increase of more force be better able, the next day [26th January 1644] to encounter them. The latter was resolved on. So, making a way with [the] Pioneers through the hedges, we marched to[wards] the town. But, after we had gone a little way, word came that the Enemy were in the Rear. So, facing about two Regiments [of Foot] and my own Regiment of Horse, commanded by Major Rousby, we relieving those that were already engaged. And so the fight began on all sides. These that fell on our Rear were those that lay [on] the other side of the town; which had passed the river [Weaver]. Those that were drawn up under their Works [about Acton Church], fell upon our Van, which was marching to the town. Thus was the battle divided; there being a quarter of a mile betwixt us. In the division first engaged, our Foot, at the beginning, gave a little ground: but our Horse recovered this, by beating the Enemy's Horse out of the lanes that flanked our Foot; which did so encourage our men as they gained now of the Enemy, so as they made them retire from hedge to hedge till, at length, they were forced to fly to their Works [Entrenchments]. But their Horse retreated in better order towards Chester, without much loss. Our other Wing [the Van], being assisted from the town, who sallied out with 700 or 800 Musketeers, beat the Enemy also back into the same Works [at Acton Church]; which we presently surrounded. [Where, as Sir T. Fairfax said in his despatch, they were caught as in a trap.] But, being in great disorder and confusion, [they] sooner yielded themselves prisoners; with all their Chief Officers, arms, Colours, and ammunition. Thus, by the mercy of GOD, was this victory obtained: being yet the more signal in that we were not to deal with young soldiers, but with men of great experience; and an Army which had ever been victorious.
  • 82. 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