Java 9 with JShell Introducing the full range of Java 9 s new features via JShell 1st Edition Gastón C. Hillar - Own the ebook now with all fully detailed chapters
Java 9 with JShell Introducing the full range of Java 9 s new features via JShell 1st Edition Gastón C. Hillar - Own the ebook now with all fully detailed chapters
com
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/
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/beginning-java-9-fundamentals-arrays-
objects-modules-jshell-and-regular-expressions-sharan/
textbookfull.com
https://textbookfull.com/product/java-9-modularity-revealed-project-
jigsaw-and-scalable-java-applications-alexandru-jecan/
textbookfull.com
https://textbookfull.com/product/introducing-java-ee-7-a-look-at-what-
s-new-juneau-josh/
textbookfull.com
https://textbookfull.com/product/all-about-java-8-lambdas-introducing-
java-8-lambdas-1st-edition-konda/
textbookfull.com
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/
textbookfull.com
https://textbookfull.com/product/pro-java-9-games-development-
leveraging-the-javafx-apis-1st-edition-wallace-jackson-auth/
textbookfull.com
https://textbookfull.com/product/java-9-revealed-for-early-adoption-
and-migration-1st-edition-kishori-sharan-auth/
textbookfull.com
https://textbookfull.com/product/java-9-modularity-patterns-and-
practices-for-developing-maintainable-applications-1st-edition-sander-
mak/
textbookfull.com
https://textbookfull.com/product/beginning-java-with-websphere-expert-
s-voice-in-java-janson-robert-w/
textbookfull.com
Java 9 with 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.
ISBN 978-1-78728-284-1
www.packtpub.com
Credits
Reviewer Proofreader
Daniel Mühlbachler Safis Editing
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 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 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
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
[ ii ]
Table of Contents
[ iii ]
Table of Contents
[ iv ]
Table of Contents
[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.
[ 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.
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 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 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 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.
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."
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;
}
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."
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.
[ 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.
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:
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
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.
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.
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:
[1]
JShell – A Read-Evaluate-Print-Loop for Java 9
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.
[2]
Another Random Document on
Scribd Without Any Related Topics
Fig. 1.—View in Tokio, showing shops and houses. (Copied from a
Photograph).
[pg 4] sometimes extending for a mile or more. Rarely ever does one
see a cross street or lane, or evidences of compactness, save that
near the centre of this long street the houses and shops often abut,
while those at the end of the streets have ample space between
them. Some villages, which from their situation have no chance of
expanding, become densely crowded: such for example is the case of
Enoshima, near Yokohama, wherein the main street runs directly
from the shore, by means of a series of steps at intervals, to a flight
of stone steps, which lead to the temples and shrines at the summit
of the island. This street is flanked on both sides by hills; and the
ravine, of which the street forms the central axis, is densely crowded
with houses, the narrowest of alley-ways leading to the houses in the
rear. A fire once started would inevitably result in the destruction of
every house in the village.
It is a curious fact that one may ride long distances in the country
without passing a single dwelling, and then abruptly enter a village.
The entrance to a village is often marked by a high mound of earth
on each side of the road, generally surmounted by a tree; or perhaps
the evidences of an old barrier are seen in the remains of gate-posts
or a stone-wall. Having passed through the village one enters the
country again, with its rice-fields and cultivated tracts, as abruptly as
he had left it. The villages vary greatly in their appearance: some are
extremely trim and pretty, with neat flower-plats in front of the
houses, and an air of taste and comfort everywhere apparent; other
villages present marked evidences of poverty, squalid houses with
dirty children swarming about them. Indeed, the most striking
contrasts are seen between the various villages one passes through
in a long overland trip in Japan.
In the cities the quarters for the wealthier classes are not so sharply
defined as with us, though the love for pleasant outlooks and
beautiful scenery tends to enhance the value of certain districts, and
consequently to bring together the wealthier classes. In nearly all the
cities, however, you will find the houses of the wealthy in the
immediate vicinity of the habitations of the poorest. In Tokio one may
find streets, or narrow [pg 6] alleys, lined with a continuous row of
the cheapest shelters; and here dwell the poorest people. Though
squalid and dirty as such places appear to the Japanese, they are
immaculate in comparison with the unutterable filth and misery of
similar quarters in nearly all the great cities of Christendom. Certainly
a rich man in Japan would not, as a general thing, buy up the land
about his house to keep the poorer classes at a distance, for the
reason that their presence would not be objectionable, since poverty
in Japan is not associated with the impossible manners of a similar
class at home.
Before proceeding with a special description of Japanese homes, a
general description of the house may render the chapters that are to
follow a little more intelligible.
While most houses of the better class have a definite porch and
vestibule, or genka, in houses of the poorer class this entrance is not
separate from the living room; and since the interior of the house is
accessible from two or three sides, one may enter it from any point.
The floor is raised a foot and a half or more from the ground, and is
covered with thick straw mats, rectangular in shape, of uniform size,
with sharp square edges, and so closely fitted that the floor upon
which they rest is completely hidden. The rooms are either square or
rectangular, and are made with absolute reference to the number of
mats they are to contain. With the exception of the guest-room few
rooms have projections or bays. In the guest-room there is at one
side a more or less deep recess divided into two bays by a slight
partition; the one nearest the verandah is called the tokonoma. In
this place hang one or more pictures, and upon its floor, which is
slightly raised above the mats, rests a flower vase, incense burner, or
some other object. The companion bay has shelves and a low closet.
Other rooms also may have recesses to accommodate a case of
drawers or shelves. Where closets and cupboards occur, they are
finished with sliding screens instead of swinging doors. In tea-houses
of two stories the stairs, which often ascend from the vicinity of the
kitchen, have beneath them a closet; and this is usually closed by a
swinging door.
The privy is at one corner of the house, at the end of the verandah;
sometimes there are two at diagonal corners of the [pg 9] house. In
the poorer class of country houses the privy is an isolated building
with low swinging door, the upper half of the door-space being open.
[pg 12]
Rein and other writers speak of the want of privacy in Japanese
dwellings, forgetting that privacy is only necessary in the midst of
vulgar and impertinent people,—a class of which Japan has the
minimum, and the so-called civilized races—the English and American
particularly—have the maximum.
The accurate way in which the base of the uprights is wrought to fit
the inequalities of the stones upon which they rest, is worthy of
notice. In the Emperor's garden we saw a two-storied house finished
in the most simple and exquisite manner. It was, indeed, like a
beautiful cabinet, though disfigured by a bright-colored foreign carpet
on its lower floor. The uprights of this structure rested on large oval
beach-worn stones buried endwise in the ground; and upon the
smooth rounded portions of the stones, which projected above the
level of the ground to a height of ten inches or more, the uprights
had been most accurately fitted (fig. 6). The effect was extremely
light and buoyant, though apparently insecure to the last degree; yet
this building had not only withstood a number of earthquake shocks,
but also the strain of severe typhoons, which during the summer
months sweep over Japan with such violence. If the building be very
small, then the frame consists of four corner-posts running to the
roof. In dwellings having a frontage of two or more rooms, other
uprights occur between the corner-posts. As the rooms [pg 17]
increase in number through the house, uprights come in the corners
of the rooms, against which the sliding-screens, or fusuma, abut. The
passage of these uprights through the room to the roof above gives a
solid constructive appearance to the house. When a house has a
verandah,—and nearly every house possesses this feature on one or
more of its sides,—another row of uprights starts in a line with the
outer edge of the verandah. Unless the verandah be very long, an
upright at each end is sufficient to support the supplementary roof
which shelters it. These uprights support a crossbeam, upon which
the slight rafters of the supplementary roof rest.
In the case of a wide gable-roof there are many ways to support the
frame, one of which is illustrated in the following outline (fig. 10).
Here a stout stick of timber runs from one end of the house to the
other on a vertical line with the ridge-pole, and on a level with the
eaves. This stick is always crowning, in order to give additional
strength. A few thick uprights start from this to support the ridge-
pole above; from these uprights beams run to the eaves; these are
mortised into the uprights, but at different levels on either side in
order not to weaken the uprights by the mortises. From these beams
run short supports to the horizontal rafters above.
The beams that support the roofs of the fire-proof buildings, or kura,
are usually rough-hewn and of ponderous dimensions. It would seem
that here, at least, the foreign method of trussing might be an
economy of material, besides giving much greater strength; and yet
the expense of reducing these beams to proper dimensions, in the
absence of saw-mills and other labor-saving machinery, with the
added expense of iron rods, bolts, etc., would more than
counterbalance the saving of material (fig. 11). In Fig. 11 is shown
the universal method of roof support; namely, horizontal beams
resting upon perpendicular walls, these in turn supporting vertical
beams, which again give support to horizontal beams. That the
Japanese have been familiar with the arch is seen in some of their
old stone bridges; but they seem as [pg 21] averse to using this
principle in their house-architecture as were the Egyptians and
Hindus. Fergusson, in his illustrated Handbook of Architecture, page
xxxv, says: “So convinced were the Egyptians and Greeks of this
principle, that they never used any other construction-expedient than
a perpendicular wall or prop, supporting a horizontal beam; and half
the satisfactory effect of their buildings arises from their adhering to
this simple though expensive mode of construction. They were
perfectly acquainted with the use of the arch and its properties, but
they knew that its employment would introduce complexity and
confusion into their designs, and therefore they wisely rejected it.
Even to the present day the Hindus refuse to use the arch, though it
has long been employed in their country by the Mahometans. As they
quaintly express it, ‘an arch never sleeps;’ and it is true that by its
thrusting and pressure it is always tending to tear a building to
pieces. In spite of all counterpoises, whenever the smallest damage
is done it hastens the ruin of a building which, if more simply
constructed, might last for ages.”
Fig. 11.—Roof-framing of a Kura.
[pg 22]
Fig. 12.—Framing of an Ordinary Two-stored House.
[pg 23]
Diagonal bracing in the frame-work of a building is never seen.
Sometimes, however, the uprights in a weak frame are supported by
braces running from the ground at an acute angle, and held in place
by wooden pins (fig. 13). Outside diagonal braces are sometimes met
with as an ornamental feature. In the province of Ise one often sees
a brace or bracket made out of an unhewn piece of timber, generally
the proximal portion of some big branch. This is fastened to an
upright, and appears to be a brace to hold up the end of a horizontal
beam that projects beyond the eaves. These braces, however, are not
even notched [pg 24] into the upright, but held in place by square
wooden pins, and are of little use as a support for the building,
though answering well to hold fishing-rods and other long poles,
which find here convenient lodgment (fig. 14).
Fig. 13.—Outside Braces.
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.
textbookfull.com