0% found this document useful (0 votes)
6 views67 pages

Java 9 with JShell Introducing the full range of Java 9 s new features via JShell 1st Edition Gastón C. Hillar pdf download

The document is a comprehensive guide to Java 9, focusing on its new features and functionalities through the use of JShell. It covers various topics such as object-oriented programming, modularity, and advanced programming concepts, structured in a series of chapters with practical exercises. The author, Gastón C. Hillar, is an experienced IT consultant and freelance author, providing insights into Java programming and its applications.

Uploaded by

sqeseejwi830
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views67 pages

Java 9 with JShell Introducing the full range of Java 9 s new features via JShell 1st Edition Gastón C. Hillar pdf download

The document is a comprehensive guide to Java 9, focusing on its new features and functionalities through the use of JShell. It covers various topics such as object-oriented programming, modularity, and advanced programming concepts, structured in a series of chapters with practical exercises. The author, Gastón C. Hillar, is an experienced IT consultant and freelance author, providing insights into Java programming and its applications.

Uploaded by

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

Java 9 with JShell Introducing the full range of

Java 9 s new features via JShell 1st Edition


Gastón C. Hillar download

https://textbookfull.com/product/java-9-with-jshell-introducing-
the-full-range-of-java-9-s-new-features-via-jshell-1st-edition-
gaston-c-hillar/

Download full version ebook from https://textbookfull.com


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

Beginning Java 9 Fundamentals: Arrays, Objects,


Modules, JShell, and Regular Expressions Sharan

https://textbookfull.com/product/beginning-java-9-fundamentals-
arrays-objects-modules-jshell-and-regular-expressions-sharan/

Java 9 Modularity Revealed: Project Jigsaw and Scalable


Java Applications Alexandru Jecan

https://textbookfull.com/product/java-9-modularity-revealed-
project-jigsaw-and-scalable-java-applications-alexandru-jecan/

Introducing Java EE 7 A Look at What s New Juneau Josh

https://textbookfull.com/product/introducing-java-ee-7-a-look-at-
what-s-new-juneau-josh/

All About Java 8 Lambdas Introducing Java 8 Lambdas 1st


Edition Konda

https://textbookfull.com/product/all-about-java-8-lambdas-
introducing-java-8-lambdas-1st-edition-konda/
Java 9 Recipes: A Problem-Solution Approach 3rd Edition
Josh Juneau

https://textbookfull.com/product/java-9-recipes-a-problem-
solution-approach-3rd-edition-josh-juneau/

Pro Java 9 Games Development: Leveraging the JavaFX


APIs 1st Edition Wallace Jackson (Auth.)

https://textbookfull.com/product/pro-java-9-games-development-
leveraging-the-javafx-apis-1st-edition-wallace-jackson-auth/

Java 9 Revealed: For Early Adoption and Migration 1st


Edition Kishori Sharan (Auth.)

https://textbookfull.com/product/java-9-revealed-for-early-
adoption-and-migration-1st-edition-kishori-sharan-auth/

Java 9 Modularity Patterns and Practices for Developing


Maintainable Applications 1st Edition Sander Mak

https://textbookfull.com/product/java-9-modularity-patterns-and-
practices-for-developing-maintainable-applications-1st-edition-
sander-mak/

Beginning Java with WebSphere Expert s Voice in Java


Janson Robert W

https://textbookfull.com/product/beginning-java-with-websphere-
expert-s-voice-in-java-janson-robert-w/
Java 9 with JShell

Introducing the full range of Java 9's new features


via JShell

Gastón C. Hillar

BIRMINGHAM - MUMBAI
Java 9 with JShell
Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2017

Production reference: 1250317

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78728-284-1
www.packtpub.com
Credits

Author Project Coordinator


Gastón C. Hillar Remzil Nisha Dcruz

Reviewer Proofreader
Daniel Mühlbachler Safis Editing

Acquisition Editor Indexer


Frank Pohlmann Tejal Daruwale Soni

Content Development Editor Graphics


Radhika Atitkar Kirk D'Penha

Technical Editor Production Coordinator


Bhagyashree Rai Melwyn Dsa

Copy Editor
Tom Jacob
About the Author

Gastón C. Hillar is Italian and has been working with computers since he was
8 years old. In the early 80s, he began programming with the legendary Texas
TI-99/4A and Commodore 64 home computers. Gastón has a bachelor's degree in
computer science (he graduated with honors). He also holds an MBA (he graduated
with an outstanding thesis). At present, Gastón is an independent IT consultant and
a freelance author who is always looking for new adventures around the world.

He was a senior contributing editor at Dr. Dobb's and has written more than a
hundred articles on software development topics. He has received the prestigious
Intel® Black Belt Software Developer award eight times. He has written many
articles about Java for Oracle Java Magazine. Gastón was also a former Microsoft
MVP in technical computing.

He is a guest blogger at Intel® Software Network (http://software.intel.com).


You can reach him at [email protected] and follow him on Twitter at
http://twitter.com/gastonhillar. Gastón's blog is http://csharpmulticore.
blogspot.com.

He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.
Acknowledgement
At the time of writing this book, I was fortunate enough to work with an excellent
team at Packt Publishing, whose contributions vastly improved the presentation
of this book. Dominic Shakeshaft and Frank Pohlmann allowed me to provide
ideas to develop this book, and I jumped into the exciting project of teaching
object-oriented and functional programming with Java 9 using JShell as the main
tool. My conversations with Frank helped me realize my vision for this book
and create a robust table of contents. Radhika Atitkar provided many sensible
suggestions regarding the text, the format, and the flow. The reader will notice
her great work. I would like to thank my technical reviewers and proofreaders for
their thorough reviews and insightful comments. I was able to incorporate some of
the knowledge and wisdom they have gained in their many years in the software
development industry. This book was possible because they gave valuable feedback.

The process of writing a book requires a huge amount of lonely hours. I wouldn't
be able to write a book without dedicating some time to play soccer against my
sons, Kevin and Brandon, and my nephew, Nicolas. Of course, I never won a match.
However, I did score a few goals.
About the Reviewer

Daniel Mühlbachler got interested in computer science shortly after entering


high school, where he later developed web applications as part of a scholarship
system for outstanding pupils.

He has a profound knowledge of web development (PHP, HTML, CSS/LESS,


and AngularJS), and he has worked with a variety of other programming languages
and systems, such as Java/Groovy, Grails, Objective-C and Swift, Matlab, Julia, C
(with Cilk), Node.js, and Linux servers.

Furthermore, he works with some database management systems based on SQL


and also some NoSQL systems, such as MongoDB and SOLR; this is also reflected
in several projects that he is currently involved in at Catalysts GmbH.

After studying abroad as an exchange student in the United Kingdom, he completed


his bachelor's degree at the Johannes Kepler University in Linz, Austria, with a thesis
on aerosol satellite data processing for mobile visualization; this is where he also
became familiar with processing large amounts of data.

Daniel enjoys solving challenging problems and is always keen on working with
new technologies, especially those related to the fields of big data, functional
programming, optimization, and NoSQL databases.

More detailed information about his experience, as well as his contact details,
can be found at www.muehlbachler.org and www.linkedin.com/in/
danielmuehlbachler.
www.PacktPub.com

eBooks, discount offers, and more


Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all
Packt books and video courses, as well as industry-leading tools to help you plan
your personal development and advance your career.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our
editorial process. To help us improve, please leave us an honest review on this book's
Amazon page at https://www.amazon.com/dp/1787282848. If you'd like to join our
team of regular reviewers, you can e-mail us at [email protected].
We award our regular reviewers with free eBooks and videos in exchange for their
valuable feedback. Help us be relentless in improving our products!
I dedicate this book to my sons, Kevin and Brandon, and my wife, Vanesa
Table of Contents
Preface vii
Chapter 1: JShell – A Read-Evaluate-Print-Loop for Java 9 1
Getting ready for our journey toward OOP with Java 9 2
Installing the required software on Windows, macOS, or Linux 2
Understanding the benefits of working with a REPL 4
Checking default imports and using auto-complete features 7
Running Java 9 code in JShell 10
Evaluating expressions 12
Working with variables, methods, and sources 13
Editing the source code in our favorite external code editor 17
Loading source code 22
Test your knowledge 24
Summary 25
Chapter 2: Real-World Objects to UML Diagrams and Java 9
via JShell 27
Identifying objects from applications requirements 28
Capturing real-world objects 34
Generating classes to create objects 41
Recognizing variables and constants 44
Identifying actions to create methods 47
Organizing classes with UML diagrams 51
Using feedback from domain experts 53
Test your knowledge 59
Summary 60

[i]
Table of Contents

Chapter 3: Classes and Instances 61


Understanding classes and instances in Java 9 61
Working with object initialization and its customization 63
Introducing garbage collection 65
Declaring classes 70
Customizing constructors and initialization 71
Understanding how garbage collection works 76
Creating instances of classes and understanding their scope 81
Exercises 82
Exercise 1 82
Exercise 2 83
Test your knowledge 83
Summary 84
Chapter 4: Encapsulation of Data 85
Understanding members composing a class 85
Declaring immutable fields 87
Working with setters and getters 91
Exploring access modifiers in Java 9 98
Combining setters, getters, and fields 99
Transforming values with setters and getters 103
Using static fields to provide class-level values 106
Using static methods to provide overridable class-level values 110
Test your knowledge 113
Summary 114
Chapter 5: Mutable and Immutable Classes 115
Creating mutable classes in Java 9 115
Working with mutable objects in JShell 118
Building immutable classes in Java 9 121
Working with immutable objects in JShell 124
Understanding the differences between mutating and non-mutating
objects 128
Learning the advantages of non-mutating objects when writing
concurrent code 131
Working with instances of the immutable String class 132
Creating the immutable version of an existing mutable class 133
Test your knowledge 137
Summary 138

[ ii ]
Table of Contents

Chapter 6: Inheritance, Abstraction, Extension,


and Specialization 139
Creating class hierarchies to abstract and specialize behavior 139
Understanding inheritance 144
Creating an abstract base class 150
Declaring classes that inherit from another class 153
Overriding and overloading methods 156
Test your knowledge 162
Summary 163
Chapter 7: Members Inheritance and Polymorphism 165
Creating concrete classes that inherit from abstract superclasses 166
Understanding polymorphism 171
Controlling overridability of members in subclasses 178
Controlling subclassing of classes 184
Creating methods that work with instances of different subclasses 191
Test your knowledge 197
Summary 198
Chapter 8: Contract Programming with Interfaces 199
Understanding how interfaces work in combination with classes 199
Declaring interfaces 202
Declaring classes that implement interfaces 206
Taking advantage of the multiple inheritance of interfaces 212
Combining class inheritance and interfaces 215
Test your knowledge 226
Summary 227
Chapter 9: Advanced Contract Programming with Interfaces 229
Working with methods receiving interfaces as arguments 229
Downcasting with interfaces and classes 234
Treating instances of an interface type as a different subclass 237
Taking advantage of default methods in interfaces in Java 9 240
Test your knowledge 245
Summary 246
Chapter 10: Maximization of Code Reuse with Generics 247
Understanding parametric polymorphism, Java 9 generics,
and generic code 247
Declaring an interface to be used as a type constraint 249
Declaring a class that conforms to multiple interfaces 251
Declaring subclasses that inherit the implementation of interfaces 257
Creating exception classes 260

[ iii ]
Table of Contents

Declaring a class that works with a constrained generic type 261


Using a generic class for multiple compatible types 267
Test your knowledge 273
Summary 274
Chapter 11: Advanced Generics 275
Creating a new interface to be used as a constraint for
a second type parameter 275
Declaring two classes that implement an interface to work
with two type parameters 276
Declaring a class that works with two constrained generic types 278
Creating instances of a generic class with two generic
type parameters 282
Test your knowledge 288
Summary 290
Chapter 12: Object-Oriented, Functional Programming,
and Lambda Expressions 291
Understanding functions and methods as first-class citizens 292
Working with functional interfaces and lambda expressions 297
Creating a functional version of array filtering 302
Creating a data repository with generics and interfaces 306
Filtering collections with complex conditions 311
Using a map operation to transform values 315
Combining a map operation with reduce 319
Chaining many operations with map and reduce 322
Working with different collectors 324
Test your knowledge 328
Summary 329
Chapter 13: Modularity in Java 9 331
Refactoring existing code to take advantage of object-oriented
programming 331
Organizing object-oriented code with the new modularity in Java 9 337
Creating modular source code 343
Compiling multiple modules with the Java 9 compiler 361
Run modularized code with Java 9 364
Test your knowledge 366
Summary 367

[ iv ]
Table of Contents

Appendix: Exercise Answers 369


Chapter 1, JShell – A Read-Evaluate-Print-Loop for Java 9 369
Chapter 2, Real-World Objects to UML Diagrams and Java 9
via JShell 370
Chapter 3, Classes and Instances 370
Chapter 4, Encapsulation of Data 371
Chapter 5, Mutable and Immutable Classes 371
Chapter 6, Inheritance, Abstraction, Extension, and Specialization 372
Chapter 7, Members Inheritance and Polymorphism 372
Chapter 8, Contract Programming with Interfaces 373
Chapter 9, Advanced Contract Programming with Interfaces 373
Chapter 10, Maximization of Code Reuse with Generics 374
Chapter 11, Advanced Generics 374
Chapter 12, Object-Oriented, Functional Programming,
and Lambda Expressions 375
Chapter 13, Modularity in Java 9 375
Index 377

[v]
Preface
Java is definitely one of the most popular programming languages of this century.
However, whenever we had to quickly explore new algorithms or new application
domains, Java didn't provide us with a simple way of executing code snippets and
print the results. As a result of this limitation, many developers started working
with other programming languages that offered a REPL (Read-Evaluate-Print-Loop)
utility, such as Scala and Python. However, many times, it was necessary to go back
to Java after the exploratory phase finished and the requirements and the algorithms
were clear.

Java 9 introduces JShell, a new utility that allows us to easily run Java 9 code
snippets and print the results. This utility is a REPL, and makes it easy for us to work
with Java as developers do with Scala and Python. JShell makes it easier to learn Java
9 and its most important features.

Object-oriented programming, also known as OOP, is a required skill in absolutely


every modern software developer job. It makes a lot of sense because OOP allows
you to maximize code reuse and minimize maintenance costs. However, learning
object-oriented programming is challenging because it includes too many abstract
concepts that require real-life examples to be easy to understand. In addition,
object-oriented code that doesn't follow best practices can easily become a
maintenance nightmare.

Java is a multi-paradigm programming language, and one of its most important


paradigms is OOP. If you want to work with Java 9, you need to master OOP in
Java. In addition, as Java 9 also grabs nice features found in functional programming
languages, it is convenient to know how to mix OOP code with functional
programing code.

[ vii ]
Preface

This book will allow you to develop high-quality reusable object-oriented code in
Java 9 with JShell. You will learn the object-oriented programming principles and
how Java 9 implements them, combined with modern functional programming
techniques. You will learn how to capture objects from real-world elements and
create object-oriented code that represents them. You will understand Java's
approach towards object-oriented code. You will maximize code reuse and reduce
maintenance costs. Your code will be easy to understand and it will work with
representations of real-life elements.

In addition, you will learn how to organize code using the new modularity feature
introduced in Java 9, and you will be ready to create complex applications.

What this book covers


Chapter 1, JShell – A Read-Evaluate-Print-Loop for Java 9, starts our journey towards
object-oriented programming with Java 9. We will learn how to launch and work
with a new utility introduced with Java 9 that will allow us to easily run Java 9 code
snippets and print its results: JShell. This utility will make it easy for us to learn
object-oriented programming.

Chapter 2, Real-World Objects to UML Diagrams and Java 9 via JShell, teaches how to
recognize objects from real-life situations. We will understand that working with
objects makes it easier to write code that is easier to understand and reuse. We will
learn how to recognize real-world elements and translate them into the different
components of the object-oriented paradigm supported in Java. We will start
organizing classes with UML (Unified Modeling Language) diagrams.

Chapter 3, Classes and Instances, shows that classes represent blueprints or templates
to generate the objects, which are also known as instances. We will design a few
classes that represent blueprints of real-life objects. We will learn about an object's
life cycle. We will work with many examples to understand how initialization works.
We will declare our first class to generate a blueprint for objects. We will customize
its initialization and test its personalized behavior in action with live examples in the
JShell. We will understand how the garbage collection works.

Chapter 4, Encapsulation of Data, teaches you the different members of a class in Java
9 and how they are reflected in members of the instances generated from a class. We
will work with instance fields, class fields, setters, getters, instance methods, and
class methods. We will generate computed properties with setters and getters. We
will take advantage of access modifiers to hide data. We will use static fields to create
values shared by all the instances of a class.

[ viii ]
Preface

Chapter 5, Mutable and Immutable Classes, introduces the differences between mutating
and non-mutating objects. First, we will create a mutable class, and then we will
build an immutable version of this class. We will learn the advantages of non-
mutating objects when writing concurrent code.

Chapter 6, Inheritance, Abstraction, Extension, and Specialization, discusses how to take


advantage of simple inheritance to specialize or extend a base class. We will design
many classes from top to bottom and we will use chained constructors. We will use
UML diagrams to design classes that inherit from another class. We will code the
classes in the interactive JShell. We will override and overload methods. We will run
code to understand how all the things we code work.

Chapter 7, Members Inheritance and Polymorphism, teaches you how to control whether
subclasses can or cannot override members. We will take advantage of one of the
most exciting object-oriented features: polymorphism. We will take advantage
of JShell to easily understand typecasting. We will declare methods that perform
operations with instances of classes.

Chapter 8, Contract Programming with Interfaces, introduces how interfaces work in


combination with classes in Java 9. The only way to have multiple inheritance in
Java 9 is through the usage of interfaces. We will learn about the declaration and
combination of multiple blueprints to generate a single instance. We will declare
interfaces with different types of requirements. Then, we will declare many classes
that implement the created interfaces. We will combine interfaces with classes to
take advantage of multiple inheritance in Java 9. We will combine inheritance for
interfaces and inheritance for classes.

Chapter 9, Advanced Contract Programming with Interfaces, dives deeper in to contract


programming with interfaces. We will work with methods that receive interfaces as
arguments. We will understand how downcasting works with interfaces and classes
and we will treat instances of an interface type as a different subclass. JShell will
allow us to easily understand the complexities of typecasting and downcasting. We
will work with more complex scenarios in which we will combine class inheritance
with interface inheritance.

Chapter 10, Maximization of Code Reuse with Generics, introduces you to working
with parametric polymorphism. We will learn how to maximize code reuse by
writing code capable of working with objects of different types, that is, instances of
classes that implement specific interfaces or whose class hierarchy includes specific
superclasses. We will work with interfaces and generics. We will create a class that
works with a constrained generic type. We will use a generic class for multiple types,
thanks to generics.

[ ix ]
Preface

Chapter 11, Advanced Generics, dives deeper in parametric polymorphism. We will


declare a class that works with two constrained generic types. We will use a generic
class with two generic type parameters in JShell. We will generalize existing classes
by taking advantage of generics in Java 9.

Chapter 12, Object-Oriented, Functional Programming, and Lambda Expressions, discusses


that functions are first-class citizens in Java 9. We will work with functional
interfaces within classes. We will use many functional programming features
included in Java 9 and combine them with everything we learned in the previous
chapters about object-oriented programming. This way, we will be able to use the
best of both worlds. We will analyze the differences between the imperative and
functional programming approach for many algorithms. We will take advantage of
lambda expressions and combine map operations with reduce.

Chapter 13, Modularity in Java 9, puts together all the pieces of the object-oriented
puzzle. We will refactor existing code to take advantage of object-oriented
programming. We will understand the usage of modular source code in Java 9. We
will work with modules to create a new Java 9 solution, organize object-oriented
code with the new modularity in Java 9, and learn many techniques of debugging
object-oriented code.

What you need for this book


You will need a computer with a dual-core CPU and at least 4 GB RAM, capable
of running JDK 9 Windows Vista SP2, Windows 7, Windows 8.x, Windows 10 or
higher, or macOS 10.9 or higher, and any Linux distribution supported by JDK 9.
Any IoT device capable of running JDK 9 will also be useful.

Who this book is for


This book can be understood by anyone who is a graduate of computer science
or someone who has just begun working as a software engineer. Basically, an
understanding of an object-oriented programming language such as Python,
C++, or indeed, an earlier Java version, is sufficient. It would be helpful to have
participated in the full product cycle of a software engineering project.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

[x]
Preface

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
Code words in text are shown as follows: "JShell allows us to call the System.out.
printf method to easily format output we want to print."

A block of code is set as follows:


double getGeneratedRectangleHeight() {
final Rectangle rectangle = new Rectangle(37, 87);
return rectangle.height;
}

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
double getGeneratedRectangleHeight() {
final Rectangle rectangle = new Rectangle(37, 87);
return rectangle.height;
}

Any command-line input or output is written as follows:


javac -version

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Click on
Accept and then click on Exit."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to [email protected],


and mention the book title via the subject of your message.

[ xi ]
Preface

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files for this book from your account at
http://www.packtpub.com. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-mailed directly
to you.

You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the
book's webpage at the Packt Publishing website. This page can be accessed by
entering the book's name in the Search box. Please note that you need to be logged in
to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder
using the latest version of:

• WinRAR / 7-Zip for Windows


• Zipeg / iZip / UnRarX for Mac
• 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.
com/PacktPublishing/Java-9-with-JShell. We also have other code bundles
from our rich catalog of books and videos available at https://github.com/
PacktPublishing/. Check them out!

[ xii ]
Preface

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/
diagrams used in this book. The color images will help you better understand the
changes in the output. You can download this file from https://www.packtpub.
com/sites/default/files/downloads/Java9withJShell_ColorImages.pdf.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated


material.

We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.

[ xiii ]
JShell – A Read-Evaluate-
Print-Loop for Java 9
In this chapter, we will start our journey toward object-oriented programming with
Java 9. You will learn how to launch and work with a new utility introduced with
Java 9 that will allow us to easily run Java 9 code snippets and print their results:
JShell. This utility will make it easy for you to learn object-oriented programming.
We will do the following:

• Get ready for our journey toward OOP (Object-Oriented Programming)


with Java 9
• Install the required software on Windows, macOS, or Linux
• Understand the benefits of working with a REPL (Read-Evaluate-Print-
Loop) utility
• Check default imports and use auto-complete features
• Run Java 9 code in JShell
• Evaluate expressions
• Work with variables, methods, and sources
• Edit the source code in our favorite external code editor
• Load source code

[1]
JShell – A Read-Evaluate-Print-Loop for Java 9

Getting ready for our journey toward


OOP with Java 9
In this book, you will learn to take advantage of all the object-oriented features
included in the Java programming language version 9, known as Java 9. Some of
the examples might be compatible with previous Java versions, such as Java 8,
Java 7, and Java 6, but it is essential to use Java 9 or later because this version is not
backwards compatible. We won't write code that is backwards compatible with
previous Java versions because our main goal is to work with Java 9 or later and to
use its syntax and all of its new features.

Most of the time, we won't use any IDE (Integrated Development Environment),
and we will take advantage of JShell and many other utilities included in the JDK.
However, you can use any IDE that provides a Java 9 REPL to work with all the
examples. You will understand the benefits of working with a REPL in the next
sections. You will definitely benefit from an IDE in the last chapter where you will
explore the new modularity features introduced with Java 9.

You don't need any previous experience with the Java programming
language to work with the examples in the book and learn how
to model and create object-oriented code with Java 9. If you have
some experience with C#, C++, Python, Swift, Objective-C, Ruby, or
JavaScript, you will be able to easily learn Java's syntax and understand
the examples. Many modern programming languages have been
borrowing features from Java and vice versa. Therefore, any knowledge
of these languages will be extremely useful.

In this chapter, we will install the required software on Windows, macOS, or Linux.
We will understand the benefits of working with a REPL, specifically, JShell, to learn
object-oriented programming. We will learn how to run Java 9 code in the JShell and
how to load the source code samples in the REPL. Finally, we will learn how to run
Java code on Windows, macOS, and Linux from the command line or terminal.

Installing the required software on


Windows, macOS, or Linux
We must download and install the latest version of JDK 9 (Java Development Kit
9) for our operating system from https://jdk9.java.net/download/. We must
accept the license agreement for Java to download the software.

[2]
Other documents randomly have
different content
CHAPTER VIII
THE LAND OF THE MANGROVE
SWAMPS
It was a long but a most interesting journey that the Doctor took
from Fantippo to Lake Junganyika. It turned out that the turtle's
home lay many miles inland in the heart of one of the wildest, most
jungly parts of Africa.
The Doctor decided to leave Gub-Gub home this time and he took
with him only Jip, Dab-Dab, Too-Too and Cheapside—who said he
wanted a holiday and that his sparrow friends could now quite well
carry on the city deliveries in his absence.
The great water snake began by taking the Doctor's party down the
coast south for some forty or fifty miles. There they left the sea,
entered the mouth of a river and started to journey inland. The
canoe (with the snake swimming alongside it) was quite the best
thing for this kind of travel so long as the river had water in it. But
presently, as they went up it, the stream grew narrower and
narrower. Till at last, like many rivers in tropical countries, it was
nothing more than the dry bed of a brook, or a chain of small pools
with long sand bars between.
Overhead the thick jungle arched and hung like a tunnel of green.
This was a good thing by day-time, as it kept the sun off better than
a parasol. And in the dry stretches of river bed, where the Doctor
had to carry or drag the canoe on home-made runners, the work
was hard and shade something to be grateful for.
At the end of the first day John Dolittle wanted to leave the canoe in
a safe place and finish the trip on foot. But the snake said they
would need it further on, where there was more water and many
swamps to cross.
As they went forward the jungle around them seemed to grow
thicker and thicker all the time. But there was always this clear alley-
way along the river bed. And though the stream's course did much
winding and twisting, the going was good.
The Doctor saw a great deal of new country, trees he had never met
before, gay-colored orchids, butterflies, ferns, birds and rare
monkeys. So his notebook was kept busy all the time with sketching
and jotting and adding to his already great knowledge of natural
history.
On the third day of travel this river bed led them into an entirely new
and different kind of country. If you have never been in a mangrove
swamp, it is difficult to imagine what it looks like. It was mournful
scenery. Flat bog land, full of pools and streamlets, dotted with tufts
of grass and weed, tangled with gnarled roots and brambling
bushes, spread out for miles and miles in every direction. It
reminded the Doctor of some huge shrubbery that had been flooded
by heavy rains. No large trees were here, such as they had seen in
the jungle lower down. Seven or eight feet above their heads was as
high as the mangroves grew and from their thin boughs long
streamers of moss hung like gray, fluttering rags.
The life, too, about them was quite different. The gayly colored birds
of the true forest did not care for this damp country of half water
and half land. Instead, all manner of swamp birds—big-billed and
long-necked, for the most part—peered at them from the sprawling
saplings. Many kinds of herons, egrets, ibises, grebes, bitterns—even
stately anhingas, who can fly beneath the water—were wading in
the swamps or nesting on the little tufty islands. In and out of the
holes about the gnarled roots strange and wondrous water creatures
—things half fish and half lizard—scuttled and quarreled with brightly
colored crabs.
For many folks it would have seemed a creepy, nightmary sort of
country, this land of the mangrove swamps. But to the Doctor, for
whom any kind of animal life was always companionable and good
intentioned, it was a most delightful new field of exploration.
They were glad now that the snake had not allowed them to leave
the canoe behind. For here, where every step you took you were
liable to sink down in the mud up to your waist, Jip and the Doctor
would have had hard work to get along at all without it. And, even
with it, the going was slow and hard enough. The mangroves spread
out long, twisting, crossing arms in every direction to bar your
passage—as though they were determined to guard the secrets of
this silent, gloomy land where men could not make a home and
seldom ever came.
Indeed, if it had not been for the giant water snake, to whom
mangrove swamps were the easiest kind of traveling, they would
never have been able to make their way forward. But their guide
went on ahead of them for hundreds of yards to lead the way
through the best openings and to find the passages where the water
was deep enough to float a canoe. And, although his head was out
of sight most of the time in the tangled distance, he kept, in the
worst stretches, a firm hold on the canoe by taking a turn about the
bowpost with his tail. And whenever they were stuck in the mud he
would contract that long, muscular body of his with a jerk and yank
the canoe forward as though it had been no more than a can tied on
the end of a string.
Dab-Dab, Too-Too and Cheapside did not, of course, bother to sit in
the canoe. They found flying from tree to tree a much easier way to
travel. But in one of these jerky pulls which the snake gave on his
living towline, the Doctor and Jip were left sitting in the mud as the
canoe was actually yanked from under them. This so much amused
the vulgar Cheapside, who was perched in a mangrove tree above
their heads, that he suddenly broke the solemn silence of the swamp
by bursting into noisy laughter.
"The canoe was yanked from under them"

"Lor' bless us, Doctor, but you do get yourself into some comical
situations! Who would think to see John Dolittle, M.D., heminent
physician of Puddleby-on-the-Marsh, bein' pulled through a mud
swamp in darkest Africa by a couple of 'undred yards of fat worm!
You've no idea how funny you look!"
"Oh, close your silly face!" growled Jip, black mud from head to foot,
scrambling back into the canoe. "It's easy for you—you can fly
through the mess."
"It 'ud make a nice football ground, this," murmured Cheapside. "I'm
surprised the Hafricans 'aven't took to it. I didn't know there was this
much mud anywhere—outside of 'Amstead 'Eath after a wet Bank
'Oliday. I wonder when we're going to get there. Seems to me we're
comin' to the end of the world—or the middle of it. 'Aven't seen a
'uman face since we left the shore. 'E's an exclusive kind of gent, our
Mr. Turtle, ain't 'e? Meself, I wouldn't be surprised if we ran into old
Noah, sitting on the wreck of the Hark, any minute.... 'Elp the Doctor
up, Jip. Look, 'e's got his chin caught under a root."
The snake, hearing Cheapside's chatter, thought something must be
wrong. He turned his head-end around and came back to see what
the matter was. Then a short halt was made in the journey while the
Doctor and Jip cleaned themselves up, and the precious notebooks,
which had also been jerked out into the mud, were rescued and
stowed in a safe place.
"Do no people at all live in these parts?" the Doctor asked the snake.
"None whatever," said the guide. "We left the lands where men dwell
behind us long ago. Nobody can live in these bogs but swamp birds,
marsh creatures and water snakes."
"How much further have we got to go?" asked the Doctor, rinsing
the mud off his hat in a pool.
"About one more day's journey," said the snake. "A wide belt of
these swamps surrounds the Secret Lake of Junganyika on all sides.
The going will become freer as we approach the open water of the
lake."
"We are really on the shores of it already, then?"
"Yes," said the serpent. "But, properly speaking, the Secret Lake
cannot be said to have shores at all—or, certainly, as you see, no
shore where a man can stand."
"Why do you call it the Secret Lake?" asked the Doctor.
"Because it has never been visited by man since the Flood," said the
giant reptile. "You will be the first to see it. We who live in it boast
that we bathe daily in the original water of the Flood. For before the
Forty Days' Rain came it was not there, they say. But when the Flood
passed away this part of the world never dried up. And so it has
remained, guarded by these wide mangrove swamps, ever since."
"What was here before the Flood then?" asked the Doctor.
"They say rolling, fertile country, waving corn and sunny hilltops,"
the snake replied. "That is what I have heard. I was not there to
see. Mudface, the turtle, will tell you all about it."
"How wonderful!" exclaimed the Doctor. "Let us push on. I am most
anxious to see him—and the Secret Lake."
CHAPTER IX
THE SECRET LAKE
During the course of the next day's travel the country became, as
the snake had foretold, freer and more open. Little by little the
islands grew fewer and the mangroves not so tangly. In the dreary
views there was less land and more water. The going was much
easier now. For miles at a stretch the Doctor could paddle, without
the help of his guide, in water that seemed to be quite deep. It was
indeed a change to be able to look up and see a clear sky overhead
once in a while, instead of that everlasting network of swamp trees.
Across the heavens the travelers now occasionally saw flights of wild
ducks and geese, winging their way eastward.
"That's a sign we're near open water," said Dab-Dab.
"Yes," the snake agreed. "They're going to Junganyika. It is the
feeding ground of great flocks of wild geese."
It was about five o'clock in the evening when they came to the end
of the little islands and mud banks. And as the canoe's nose glided
easily forward into entirely open water they suddenly found
themselves looking across a great inland sea.
The Doctor was tremendously impressed by his first sight of the
Secret Lake. If the landscape of the swamp country had been
mournful this was even more so. No eye could see across it. The
edge of it was like the ocean's—just a line where the heavens and
the water meet. Ahead to the eastward—the darkest part of the
evening sky—even this line barely showed, for now the murky
waters and the frowning night blurred together in an inky mass. To
the right and left the Doctor could see the fringe of the swamp trees
running around the lake, disappearing in the distance North and
South.
Out in the open great banks of gray mist rolled and joined and
separated as the wailing wind pushed them fretfully hither and
thither over the face of the waters.
"My word!" the Doctor murmured in a quiet voice. "Here one could
almost believe that the Flood was not over yet!"
"Jolly place, ain't it?" came Cheapside's cheeky voice from the stern
of the canoe. "Give me London any day—in the worst fog ever. This
is a bloomin' eels' country. Look at them mist shadows skatin' round
the lake. Might be old Noah and 'is family, playin' 'Ring-a-ring-a-rosy'
in their night-shirts, they're that lifelike."
"The mists are always there," said the snake—"always have been. In
them the first rainbow shone."
"Well," said the sparrow, "I'd sell the whole place cheap if it was
mine—mists and all. 'Ow many 'undred miles of this bonny blue
ocean 'ave we got to cross before we reach our Mr. Mudface?"
"Not very many," said the snake. "He lives on the edge of the lake a
few miles to the North. Let us hurry and try to reach his home
before darkness falls."
Once more, with the guide in front, but this time at a much better
pace, the party set off.
As the light grew dimmer the calls of several night birds sounded
from the mangroves on the left. Too-Too told the Doctor that many
of these were owls, but of kinds that he had never seen or met with
before.
"Yes," said the Doctor. "I imagine there are lots of different kinds of
birds and beasts in these parts that can be found nowhere else in
the world."
At last, while it was still just light enough to see, the snake swung
into the left and once more entered the outskirts of the mangrove
swamps. Following him with difficulty in the fading light, the Doctor
was led into a deep glady cove. At the end of this the nose of the
canoe suddenly bumped into something hard. The Doctor was about
to lean out to see what it was when a deep, deep bass voice spoke
out of the gloom quite close to him.
"Welcome, John Dolittle. Welcome to Lake Junganyika."
Then looking up, the Doctor saw on a mound-like island the shape of
an enormous turtle—fully twelve feet across the shell—standing
outlined against the blue-black sky.

"The Doctor saw the shape of an enormous turtle"


The long journey was over at last.
Doctor Dolittle did not at any time believe in traveling with very
much baggage. And all that he had brought with him on this journey
was a few things rolled up in a blanket—and, of course, the little
black medicine-bag. Among those things, luckily, however, were a
couple of candles. And if it had not been for them he would have
had hard work to land safely from the canoe.
Getting them lighted in the wind that swept across the lake was no
easy matter. But to protect their flame Too-Too wove a couple of
little lanterns out of thin leaves, through which the light shone dimly
green but bright enough to see your way by.
To his surprise, the Doctor found that the mound, or island, on
which the turtle lived was not made of mud, though muddy
footprints could be seen all over it. It was made of stone—of stones
cut square with a chisel.
While the Doctor was examining them with great curiosity the turtle
said:
"They are the ruins of a city. I used to be content to live and sleep in
the mud. But since my gout has been so bad I thought I ought to
make myself something solid and dry to rest on. Those stones are
pieces of a king's house."
"Pieces of a house—of a city!" the Doctor exclaimed, peering into
the wet and desolate darkness that surrounded the little island. "But
where did they come from?"
"From the bottom of the lake," said the turtle. "Out there," Mudface
nodded toward the gloomy wide-stretching waters, "there stood,
thousands of years ago, the beautiful city of Shalba. Don't I know,
when for long enough I lived in it? Once it was the greatest and
fairest city ever raised by men and King Mashtu of Shalba the
proudest monarch in the world. Now I, Mudface the turtle, make a
nest in the swamp out of the ruins of his palace. Ha! Ha!"
"You sound bitter," said the Doctor. "Did King Mashtu do you any
harm?"
"I should say he did," growled Mudface. "But that belongs to the
story of the Flood. You have come far. You must be weary and in
need of food."
"Well," said the Doctor, "I am most anxious to hear the story. Does it
take long to tell?"
"About three weeks would be my guess," whispered Cheapside.
"Turtles do everything slow. Something tells me that story is the
longest story in the world, Doctor. Let's get a nap and a bite to eat
first. We can hear it just as well to-morrow."
So, in spite of John Dolittle's impatience, the story was put off till the
following day. For the evening meal Dab-Dab managed to scout
around and gather together quite a nice mess of fresh-water
shellfish and Too-Too collected some marsh berries that did very well
for dessert.
Then came the problem of how to sleep. This was not so easy,
because, although the foundations of the turtle's mound were of
stone, there was hardly a dry spot on the island left where you could
lie down. The Doctor tried the canoe. But it was sort of cramped and
uncomfortable for sleeping, and now even there, too, the mud had
been carried by Dab-Dab's feet and his own. In this country the
great problem was getting away from the mud.
"When Noah's family first came out of the Ark," said the turtle, "they
slept in little beds which they strung up between the stumps of the
drowned trees."
"Ah, hammocks!" cried the Doctor. "Of course—the very thing!"
Then, with Jip's and Dab-Dab's help, he constructed a very
comfortable basket-work hammock out of willow wands and
fastened it between two larger mangroves. Into this he climbed and
drew the blanket over him. Although the trees leaned down toward
the water with his weight, they were quite strong and their
bendiness acted like good bed springs.

"The trees bent down with his weight"

The moon had now risen and the weird scenery of Junganyika was
all green lights and blue shadows. As the Doctor snuffed out his
candles and Jip curled himself up at his feet the turtle suddenly
started humming a tune in his deep bass voice, waving his long neck
from side to side in the moonlight.
"What is that tune you are humming?" asked the Doctor.
"That's the 'Elephants' March,'" said the turtle. "They always played
it at the Royal Circus of Shalba for the elephants' procession."
"Let's 'ope it 'asn't many verses," grumbled Cheapside, sleepily
putting his head under his wing.
The sun had not yet risen on the gloomy waters of Lake Junganyika
before Jip felt the Doctor stirring in his hammock, preparing to get
up.
Presently Dab-Dab could be heard messing about in the mud below,
bravely trying to get breakfast ready under difficult conditions.
Next Cheapside, grumbling in a sleepy chirp, brought his head out
from under his wing, gave the muddy scenery one look and popped
it back again.
But it was of little use to try to get more sleep now. The camp was
astir. John Dolittle, bent on the one idea of hearing that story, had
already swung himself out of his hammock and was now washing his
face noisily in the lake. Cheapside shook his feathers, swore a few
words in Cockney and flew off his tree down to the Doctor's side.
"The Doctor was washing his face in the lake"

"Look 'ere, Doctor," he whispered, "this ain't an 'olesome place to


stay at all. I'm all full of cramp from the damp night air. You'd get
webfooted if you loitered in this country long. Listen, you want to be
careful about gettin' old Mudface started on his yarn spinning. D'yer
know what 'e reminds me of? Them old Crimea War veterans. Once
they begin telling their reminiscences there's no stoppin' 'em. 'E
looks like one, too, with that long, scrawny neck of 'is. Tell 'im to
make it short and sweet—just to give us the outline of his troubles,
like, see? The sooner we can shake the mud of this place off our
feet and make tracks for Fantippo the better it'll be for all of us."
Well, when breakfast had been disposed of the Doctor sharpened his
pencil, got out a notebook and, telling Too-Too to listen carefully, in
case he should miss anything, he asked the turtle to begin the story
of the Flood.
Cheapside had been right. Although it did not take a fortnight to tell
it did take a very full day. Slowly and evenly the sun rose out of the
East, passed across the heavens and sank down into the West. And
still Mudface went murmuring on, telling of all the wonders he had
seen in days long ago, while the Doctor's pencil wiggled untiringly
over the pages of his notebook. The only interruptions were when
the turtle paused to lean down and moisten his long throat with the
muddy water of the lake, or when the Doctor stopped him to ask a
question on the natural history of antediluvian times.
Dab-Dab prepared lunch and supper and served them as silently as
she could, so as not to interrupt; but for the Doctor they were very
scrappy meals. On into the night the story went. And now John
Dolittle wrote by candle-light, while all his pets, with the exception of
Too-Too, were already nodding or dozing.
At last, about half past ten—to Cheapside's great relief—the turtle
pronounced the final words.
"And that, John Dolittle, is the end of the story of the Flood by one
who saw it with his own eyes."
For some time after the turtle finished no one spoke. Even the
irreverent Cheapside was silent. Little bits of stars, dimmed by the
light of a half-full moon, twinkled like tiny eyes in the dim blue dome
that arched across the lake. Away off somewhere among the tangled
mangroves an owl hooted from the swamp and Too-Too turned his
head quickly to listen. Dab-Dab, the economical housekeeper, seeing
the Doctor close his notebook and put away his pencil, blew out the
candle.
"Dab-Dab, the economical housekeeper, blew out the candle"

At last the Doctor spoke:


"Mudface, I don't know when, in all my life I have listened to a story
that interested me so much. I—I'm glad I came."
"I too am glad, John Dolittle. You are the only one in the world now
who understands the speech of animals. And if you had not come
my story of the Flood could not have been told. I'm getting very old
and do not ever move far away from Junganyika."
"Would it be too much to ask you?" said the Doctor, "to get me some
souvenir from the city below the lake?"
"Not at all," said the turtle. "I'll go down and try to get you
something right away."
Slowly and smoothly, like some unbelievable monster of former days,
the turtle moved his great bulk across his little island and slid himself
into the lake without splashing or disturbance of any kind. Only a
gentle swirling in the water showed where he had disappeared.
In silence they all waited—the animals now, for the moment,
reawakened and full of interest. The Doctor had visions of his
enormous friend moving through the slime of centuries at the
bottom of the lake, hunting for some souvenir of the great
civilization that passed away with the Flood. He hoped that he would
bring a book or something with writing on it.
Instead, when at last he reappeared wet and shining in the
moonlight, he had a carved stone window-sill on his back which
must have weighed over a ton.
"Lor' bless us!" muttered Cheapside. "What a wonderful piano-mover
'e would make to be sure! Great Carter Patterson! Does 'e think the
Doctor's goin' to 'ang that on 'is watch-chain?"
"It was the lightest thing I could find," said the turtle, rolling it off
his back with a thud that shook the island. "I had hoped I could get
a vase or a plate or something you could carry. But all the smaller
objects are now covered in fathoms of mud. This I broke off from
the second story of the palace—from the queen's bedroom window.
I thought perhaps you'd like to see it anyway, even if it was too
much for you to carry home. It's beautifully carved. Wait till I wash
some of the mud off it."
The candles were lighted again and after the carvings had been
cleaned the Doctor examined them with great care and even made
sketches of some of them in his notebook.
By the time the Doctor had done, all his party, excepting Too-Too,
had fallen asleep. It was only when he heard Jip suddenly snore
from the hammock that he realized how late it was. As he blew out
the candles again he found that it was very dark, for now the moon
had set. He climbed into bed and drew the blankets over him.
CHAPTER X
THE POSTMASTER GENERAL'S LAST
ORDER
When Dab-Dab roused the party next morning the sun was shining
through the mist upon the lake doing its best to brighten up the
desolate scenery around them.
Poor Mudface awoke with an acute attack of gout. He had not been
bothered by this ailment since the Doctor's arrival. But now he could
scarcely move at all without great pain. And Dab-Dab brought his
breakfast to him where he lay.
John Dolittle was inclined to blame himself for having asked him to
go hunting in the lake for souvenirs the night before.
"I'm afraid that was what brought on the attack," said the Doctor,
getting out his little black bag from the canoe and mixing some
medicines. "But you know you really ought to move out of this damp
country to some drier climate. I am aware that turtles can stand an
awful lot of wet. But at your age one must be careful, you know."
"Mixing the turtle's medicine"

"There isn't any other place I like as well," said Mudface. "It's so
hard to find a country where you're not disturbed these days."
"Here, drink this," the Doctor ordered, handing him a tea-cup full of
some brown mixture. "I think you will find that that will soon relieve
the stiffness in your front legs."
The turtle drank it down. And in a minute or two he said he felt
much better and could now move his legs freely without pain.
"It's a wonderful medicine, that," said he. "You are surely a great
Doctor. Have you got any more of it?"
"I will make up several bottles of the mixture and leave them with
you before I go," said John Dolittle. "But you really ought to get on
high ground somewhere. This muddy little hummock is no place for
you to live. Isn't there a regular island in the lake, where you could
make your home—if you're determined not to leave the Junganyika
country?"
"Not one," said the turtle. "It's all like this, just miles and miles of
mud and water. I used to like it—in fact I do still. I wouldn't wish for
anything better if it weren't for this wretched gout of mine."
"Well," said the Doctor, "if you haven't got an island we must make
one for you."
"Make one!" cried the turtle. "How would you go about it?"
"I'll show you very shortly," said John Dolittle. And he called
Cheapside to him.
"Will you please fly down to Fantippo," he said to the City Manager,
"and give this message to Speedy-the-Skimmer. And ask him to send
it out to all the postmasters of the branch offices: The Swallow Mail
is very shortly to be closed—at all events for a considerable time. I
must now be returning to Puddleby and it will be impossible for me
to continue the service in its present form after I have left No-Man's-
Land. I wish to convey my thanks to all the birds, postmasters,
clerks and letter-carriers who have so generously helped me in this
work. The last favor which I am going to ask of them is a large one;
and I hope they will give me their united support in it. I want them
to build me an island in the middle of Lake Junganyika. It is for
Mudface the turtle, the oldest animal living, who in days gone by did
a very great deal for man and beast—for the whole world in fact—
when the earth was passing through the darkest chapters in all its
history. Tell Speedy to send word to all bird leaders throughout the
world. Tell him I want as many birds as possible right away to build
a healthy home where this brave turtle may end his long life in
peace. It is the last thing I ask of the post office staff and I hope
they will do their best for me."
Cheapside said that the message was so long he was afraid he
would never be able to remember it by heart. So John Dolittle told
him to take it down in bird scribble and he dictated it to him all over
again.
That letter, the last circular order issued by the great Postmaster
General to the staff of the Swallow Mail, was treasured by Cheapside
for many years. He hid it under his untidy nest in St. Edmund's left
ear on the south side of the chancel of St. Paul's Cathedral. He
always hoped that the pigeons who lived in the front porch of the
British Museum would some day get it into the Museum for him. But
one gusty morning, when men were cleaning the outside of the
cathedral, it got blown out of St. Edmund's ear and, before
Cheapside could overtake it, it sailed over the housetops into the
river and sank.
The sparrow got back to Junganyika late that afternoon. He reported
that Speedy had immediately, on receiving the Doctor's message,
forwarded it to the postmasters of the branch offices with orders to
pass it on to all the bird-leaders everywhere. It was expected that
the first birds would begin to arrive here early the following morning.
It was Speedy himself who woke the Doctor at dawn the next day.
And while breakfast was being eaten he explained to John Dolittle
the arrangements that had been made.
The work, the Skimmer calculated, would take three days. All birds
had been ordered to pick up a stone or a pebble or a pinch of sand
from the seashore on their way and bring it with them. The larger
birds (who would carry stones) were to come first, then the middle-
sized birds and then the little ones with sand.
Soon, when the sky over the lake was beginning to fill up with
circling ospreys, herons and albatrosses, Speedy left the Doctor and
flew off to join them. There, taking up a position in the sky right
over the centre of the lake, he hovered motionless, as a marker for
the stone-droppers. Then the work began.
All day long a never-ending stream of big birds, a dozen abreast,
flew up from the sea and headed across Lake Junganyika. The line
was like a solid black ribbon, the birds, dense, packed and close,
beak to tail. And as each dozen reached the spot where Speedy
hovered, twelve stones dropped into the water. The procession was
so continuous and unbroken that it looked as though the sky were
raining stones. And the constant roar of them splashing into the
water out of the heavens could be heard a mile off.

"A never-ending stream of big birds"


The lake in the centre was quite deep. And of course tons and tons
of stone would have to be dropped before the new island would
begin to show above the water's surface. This gathering of birds was
greater even than the one the Doctor had addressed in the hollow of
No-Man's-Land. It was the biggest gathering of birds that had ever
been seen. For now not only the leaders came but thousands and
millions of every species. John Dolittle got tremendously excited and
jumping into his canoe he started to paddle out nearer to the work.
But Speedy grew impatient that the top of the stone-pile was not yet
showing above the water; and he gave the order to double up the
line—and then double again, as still more birds came to help from
different parts of the world. And soon, with a thousand stones falling
every fraction of a second, the lake got so rough that the Doctor had
to put back for the turtle's hummock lest his canoe capsize.
All that day, all that night and half the next day, this continued. At
last about noon on the morrow the sound of the falling stones began
to change. The great mound of seething white water, like a fountain
in the middle of the lake, disappeared; and in its place a black spot
showed. The noise of splashing changed to the noise of stone
rattling on stone. The top of the island had begun to show.
"It's like the mountains peeping out after the Flood," Mudface
muttered to the Doctor.
Then Speedy gave the order for the middle-sized birds to join in;
and soon the note of the noise changed again—shriller—as tons and
tons of pebbles and gravel began to join the downpour.
Another night and another day went by, and at dawn the gallant
Skimmer came down to rest his weary wings; for the workers did not
need a marker any longer—now that a good-sized island stood out
on the bosom of the lake for the birds to drop their burdens on.
Bigger and bigger grew the home-made land and soon Mudface's
new estate was acres wide. Still another order from Speedy; and
presently the rattling noise changed to a gentle hiss. The sky now
was simply black with birds; the pebble-shower had ceased; it was
raining sand. Last of all, the birds brought seeds: grass seeds, the
seeds of flowers, acorns and the kernels of palms. The turtle's new
home was to be provided with turf, with wild gardens, with shady
avenues to keep off the African sun.
When Speedy came to the hummock and said, "Doctor, it is
finished," Mudface gazed thoughtfully out into the lake and
murmured:
"Now proud Shalba is buried indeed: she has an island for a
tombstone! It's a grand home you have given me, John Dolittle.—
Alas, poor Shalba!—Mashtu the king passes. But Mudface the turtle
—lives on!"
CHAPTER XI
GOOD-BYE TO FANTIPPO
Mudface's landing on his new home was quite an occasion. The
Doctor paddled out alongside of him till they reached the island.
Until he set foot on it, John Dolittle himself had not realized what a
large piece of ground it was. It was more than a quarter of a mile
across. Round in shape, it rose gently from the shores to the flat
centre, which was a good hundred feet above the level of the lake.
Mudface was tremendously pleased with it; climbing laboriously to
the central plateau—from where you could see great distances over
the flat country around—he said he was sure his health would
quickly improve in this drier air.
Dab-Dab prepared a meal—the best she could in the circumstances
—to celebrate what she called the turtle's house-warming. And
everyone sat down to it; and there was much gayety and the Doctor
was asked to make a speech in honor of the occasion.
"Dab-Dab prepared a meal"

Cheapside was dreadfully afraid that Mudface would get up to make


a speech in reply and that it would last into the following day. But to
the sparrow's relief the Doctor, immediately he had finished, set
about preparations for his departure.
He made up the six bottles of gout mixture and presented them to
Mudface with instructions in how it should be taken. He told him that
although he was closing up the post office for regular service it
would always be possible to get word to Puddleby. He would ask
several birds of passage to stop here occasionally; and if the gout
got any worse he wanted Mudface to let him know by letter.
The old turtle thanked him over and over again and the parting was
a very affecting one. When at last the goodbyes were all said, they
got into the canoe and set out on the return journey.
Reaching the mouth of the river at the southern end of the lake they
paused a moment before entering the mangrove swamps and looked
back. And there in the distance they could just see the shape of the
old turtle standing on his new island, watching them. They waved to
him and pushed on.
"He looks just the same as we saw him the night we arrived," said
Dab-Dab—"you remember? Like a statue on a pedestal against the
sky."
"Poor old fellow!" murmured the Doctor. "I do hope he will be all
right now.... What a Wonderful life!—What a wonderful history!"
"Didn't I tell you, Doctor," said Cheapside, "that it was going to be
the longest story in the world?—Took a day and half a night to tell."
"Ah, but it's a story that nobody else could tell," said John Dolittle.
"Good thing too," muttered the Sparrow. "It would never do if there
was many of 'is kind spread around this busy world.—Of course,
meself, I don't believe a word of the yarn. I think he made it all up.
'E 'ad nothin' else to do—sittin' there in the mud, century after
century, cogitatin'."
The journey down through the jungle was completed without
anything special happening. But when they reached the sea and
turned the bow of the canoe westward they came upon a very
remarkable thing. It was an enormous hole in the beach—or rather a
place where the beach had been taken away bodily. Speedy told the
Doctor that it was here that the birds had picked up the stones and
sand on their way to Junganyika. They had literally carried acres of
the seashore nearly a thousand miles inland. Of course in a few
months the action of the surf filled in the hole, so that the place
looked like the rest of the beach.
But that is why, when many years later some learned geologists
visited Lake Junganyika, they said that the seashore gravel on an
island there was a clear proof that the sea had once flowed through
that neighborhood. Which was true—in the days of the Flood. But
the Doctor was the only scientist who knew that Mudface's island,
and the stones that made it, had quite a different history.
On his arrival at the post office the Doctor was given his usual warm
reception by the king and dignitaries of Fantippo who paddled out
from the town to welcome him back.
Tea was served at once; and His Majesty seemed so delighted at
renewing this pleasant custom that John Dolittle was loath to break
the news to him that he must shortly resign from the Foreign Mail
Service and sail for England. However, while they were chatting on
the veranda of the houseboat a fleet of quite large sailing vessels
entered the harbor. These were some of the new merchant craft of
Fantippo which plied regularly up and down the coast, trading with
other African countries. The Doctor pointed out to the king that
mails intended for foreign lands could now be quite easily taken by
these boats to the bigger ports on the coast where vessels from
Europe called every week.
From that the Doctor went on to explain to the King, that much as
he loved Fantippo and its people, he had many things to attend to in
England and must now be thinking of going home. And of course as
none of the natives could talk bird-language, the Swallow Mail would
have to be replaced by the ordinary kind of post office.
The Doctor found that His Majesty was much more distressed at the
prospect of losing his good white friend and his afternoon tea on the
houseboat than at anything else which the change would bring. But
he saw that the Doctor really felt he had to go; and at length, with
tears falling into his tea-cup, he gave permission for the Postmaster
General of Fantippo to resign.
Great was the rejoicing among the Doctor's pets and the patient
swallows when the news got about that John Dolittle was really
going home at last. Gub-Gub and Jip could hardly wait while the last
duties and ceremonies of closing the houseboat to the public and
transferring the Foreign Mails Service to the office in the town were
performed. Dab-Dab bustled cheerfully from morning to night while
Cheapside never ceased to chatter of the glories of London, the
comforts of a city life and all the things he was going to do as soon
as he got back to his beloved native haunts.
There was no end to the complimentary ceremonies which the good
King Koko and his courtiers performed to honor the departing
Doctor. For days and days previous to his sailing, canoes came and
went between the town and the houseboat bearing presents to show
the good will of the Fantippans. During all this, having to keep
smiling the whole time, the Doctor got sadder and sadder at leaving
his good friends. And he was heartily glad when the hour came to
pull up the anchor and put to sea.
People who have written the history of the Kingdom of Fantippo all
devote several chapters to a mysterious white man who in a very
short space of time made enormous improvements in the mail, the
communications, the shipping, the commerce, the education and the
general prosperity of the country. Indeed it was through John
Dolittle's quiet influence that King Koko's reign came to be looked
upon as the Golden Age in Fantippan history. A wooden statue still
stands in the market-place to his memory.
"A wooden statue still stands to his memory"

The excellent postal service continued after he left. The stamps with
Koko's face on them were as various and as beautiful as ever. On the
occasion of the first annual review of the Fantippo Merchant Fleet a
very fine two-shilling stamp was struck in commemoration, showing
His Majesty inspecting his new ships through a lollipop quizzing-
glass. The King himself became a stamp-collector and his album was
as good as a family photo-album, containing as it did so many
pictures of himself. The only awkward incident that happened in the
record of the post office which the Doctor had done so much to
improve was when some ardent stamp-collectors, wishing to make
the modern stamps rare, plotted to have the King assassinated in
order that the current issues should go out of date. But the plot was
happily discovered before any harm was done.
Years afterwards, the birds visiting Puddleby told the Doctor that the
King still had the flowers in the window-boxes of his old houseboat
carefully tended and watered in his memory. His Majesty, they said,
never gave up the fond hope that some day his good white friend
would come back to Fantippo with his kindly smile, his instructive
conversation and his jolly tea-parties on the post office veranda.

THE END
*** END OF THE PROJECT GUTENBERG EBOOK DOCTOR
DOLITTLE'S POST OFFICE ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like