100% found this document useful (2 votes)
21 views

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

The document promotes a collection of Java 9 ebooks available for download at textbookfull.com, highlighting various titles that cover new features, modularity, and programming fundamentals. It includes information about the author, Gastón C. Hillar, and his background in computer science and software development. Additionally, the document provides details on the structure and content of the book 'Java 9 with JShell' and other related resources.

Uploaded by

kenirykewley
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
100% found this document useful (2 votes)
21 views

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

The document promotes a collection of Java 9 ebooks available for download at textbookfull.com, highlighting various titles that cover new features, modularity, and programming fundamentals. It includes information about the author, Gastón C. Hillar, and his background in computer science and software development. Additionally, the document provides details on the structure and content of the book 'Java 9 with JShell' and other related resources.

Uploaded by

kenirykewley
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/ 56

Explore the full ebook collection and download it now at textbookfull.

com

Java 9 with JShell Introducing the full range of


Java 9 s new features via JShell 1st Edition
Gastón C. Hillar

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

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

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/

textbookfull.com

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/

textbookfull.com

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/

textbookfull.com

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/

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

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/

textbookfull.com

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/

textbookfull.com

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/
textbookfull.com

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/

textbookfull.com
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]
Another Random Document on
Scribd Without Any Related Topics
Fig. 1.—View in Tokio, showing shops and houses. (Copied from a
Photograph).

Fig. 2.—View in Tokio, showing temples and gardens. (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.

It is difficult to imagine a more dreary and dismal sight than the


appearance of some of these village streets on a rainy night. No
brightly-lighted window cheers the traveller; only [pg 5] lines of light
glimmer through the chinks of the wooden shutters with which every
house is closed at night. On pleasant evenings when the paper
screens alone are closed, a ride through a village street is often
rendered highly amusing by the grotesque shadow-pictures which the
inmates are unconsciously projecting in their movements to and fro.
Fig. 3.—View of Enoshima (Copied from a Photograph).

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.

The first sight of a Japanese house,—that is, a house of the people,—


is certainly disappointing. From the infinite variety and charming
character of their various works of art, as we had seen them at
home, we were anticipating new delights and surprises in the
character of the house; nor were we on more intimate acquaintance
to be disappointed. As an American familiar with houses of certain
types, with conditions among them signifying poverty and
shiftlessness, and other conditions signifying refinement and wealth, I
was not competent to judge the relative merits of a Japanese house.

The first sight, then, of a Japanese house is disappointing; it is


unsubstantial in appearance, and there is a meagreness of color.
Being unpainted, it suggests poverty; and this absence of paint, with
the gray and often rain-stained color of the boards, leads one to
compare it with similar unpainted buildings at home,—and these are
usually barns and sheds in the country, and the houses of the poorer
people in the city. With one's eye accustomed to the bright contrasts
of American houses with their white, or light, painted surfaces;
rectangular windows, [pg 7] black from the shadows within, with
glints of light reflected from the glass; front door with its pretentious
steps and portico; warm red chimneys surmounting all, and a general
trimness of appearance outside, which is by no means always
correlated with like conditions within,—one is too apt at the outset to
form a low estimate of a Japanese house. An American finds it
difficult indeed to consider such a structure as a dwelling, when so
many features are absent that go to make up a dwelling at home,—
no doors or windows such as he had been familiar with; no attic or
cellar; no chimneys, and within no fire-place, and of course no
customary mantle; no permanently enclosed rooms; and as for
furniture, no beds or tables, chairs or similar articles,—at least, so it
appears at first sight.
One of the chief points of difference in a Japanese house as
compared with ours lies in the treatment of partitions and outside
walls. In our houses these are solid and permanent; and when the
frame is built, the partitions form part of the framework. In the
Japanese house, on the contrary, there are two or more sides that
have no permanent walls. Within, also, there are but few partitions
which have similar stability; in their stead are slight sliding screens
which run in appropriate grooves in the floor and overhead. These
grooves mark the limit of each room. The screens may be opened by
sliding them back, or they may be entirely removed, thus throwing a
number of rooms into one great apartment. In the same way the
whole side of a house may be flung open to sunlight and air. For
communication between the rooms, therefore, swinging doors are not
necessary. As a substitute for windows, the outside screens, or shōji,
are covered with white paper, allowing the light to be diffused
through the house.

Where external walls appear they are of wood unpainted, or painted


black; and if of plaster, white or dark slate colored. In certain classes
of buildings the outside wall, to a height of several [pg 8] feet from
the ground, and sometimes even the entire wall, may be tiled, the
interspaces being pointed with white plaster. The roof may be either
lightly shingled, heavily tiled, or thickly thatched. It has a moderate
pitch, and as a general thing the slope is not so steep as in our roofs.
Nearly all the houses have a verandah, which is protected by the
widely-overhanging eaves of the roof, or by a light supplementary
roof projecting from beneath the eaves.

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.

In city houses the kitchen is at one side or corner of the house;


generally in an L, covered with a pent roof. This apartment is often
towards the street, its yard separated from other areas by a high
fence. In the country the kitchen is nearly always under the main
roof. In the city few out-buildings such as sheds and barns are seen.
Accompanying the houses of the better class are solid, thick-walled,
one or two storied, fire-proof buildings called kura, in which the
goods and chattels are stored away at the time of a conflagration.
These buildings, which are known to the foreigners as “godowns,”
have one or two small windows and one door, closed by thick and
ponderous shutters. Such a building usually stands isolated from the
dwelling, though often in juxtaposition; and sometimes, though
rarely, it is used as a domicile.

In the gardens of the better classes summer-houses and shelters of


rustic appearance and diminutive proportions are often seen. Rustic
arbors are also to be seen in the larger gardens. Specially
constructed houses of quaint design and small size are not
uncommon; in these the ceremonial tea-parties take place. High
fences, either of board or bamboo, or solid walls of mud or tile with
stone foundations, surround the house or enclose it from the street.
Low rustic fences border the gardens in the suburbs. Gateways of
various styles, some of imposing design, form the entrances; as a
general thing they are either rustic and light, or formal and massive.

Whatever is commonplace in the appearance of the house is towards


the street, while the artistic and picturesque face is turned towards
the garden, which may be at one side or in the rear of the house,—
usually in the rear. Within these plain and unpretentious houses there
are often to be seen marvels of exquisite carving, [pg 10] and the
perfection of cabinet work; and surprise follows surprise, as one
becomes more fully acquainted with the interior finish of these
curious and remarkable dwellings.

In the sections which are to follow, an attempt will be made by


description and sketches to convey some idea of the details
connected with the structure and inside finish of the Japanese house.

There is no object in Japan that seems to excite more diverse and


adverse criticism among foreigners than does the Japanese house; it
is a constant source of perplexity and annoyance to most of them. An
Englishman particularly, whom Emerson says he finds “to be him of
all men who stands firmest in his shoes,” recognizes but little merit in
the apparently frail and perishable nature of these structures. He
naturally dislikes the anomaly of a house of the lightest description
oftentimes sustaining a roof of the most ponderous character, and
fairly loathes a structure that has no king-post, or at least a queen-
post, truss; while the glaring absurdity of a house that persists in
remaining upright without a foundation, or at least without his kind of
a foundation, makes him furious. The mistake made by most writers
in criticising Japanese house-structure, and indeed many other
matters connected with that country, is that these writers do not
regard such matters from a Japanese stand-point. They do not
consider that the nation is poor, and that the masses are in poverty;
nor do they consider that for this reason a Japanese builds such a
house as he can afford, and one that after all is as thoroughly
adapted to his habits and wants as ours is to our habits and wants.

The observation of a Japanese has shown him that from generation


to generation the houses of his people have managed to sustain
themselves; and if in his travels abroad he has chanced to visit
England, he will probably recall the fact that he saw [pg 11] more
dilapidated tenements, tumble-down shanties, broken-backed farm-
houses, cracked walls, and toppling fences in a single day in that
virtuous country where there are no typhoons or earthquakes, than
he would see in a year's travel in his own country.

When one of these foreign critical writers contemplates the


framework of a Japanese house, and particularly the cross-beams of
the roof, and finds no attempt at trussing and bracing, he is seized
with an eager desire to go among these people as a missionary of
trusses and braces,—it is so obvious that much wood might be saved!
In regard to the Japanese house-frame, however, it is probable that
the extra labor of constructing braces and trusses would not
compensate for the difference saved in the wood.

Rein, in his really admirable book on Japan, says “the Japanese


house lacks chiefly solidity and comfort.” If he means comfort for
himself and his people, one can understand him; if he means comfort
for the Japanese, then he has not the faintest conception of the solid
comfort a Japanese gets out of his house. Rein also complains of the
evil odors of the closet arrangements, though his complaints refer
more particularly to the crowded inns, which are often in an
exceedingly filthy condition as regards these necessary conveniences,
—and one is led to inquire what the Japanese would think of similar
features in Germany, where in the larger cities the closet may be
seen opening directly into the front hall, and in some cases even from
the dining-room! Bad as some of these conditions are in Japan, they
are mild in comparison with like features in Germany. The filthy state
of the larger cities, in this respect, may be indicated by the fact that
the death-rate of Munich a few years ago was forty-four, and
Kaulbach died of cholera in that city in mid-winter! Indeed, the
presence of certain features in every bed-chamber at home and
abroad are looked upon as surpassingly filthy by every Japanese,—as
they truly are.

[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.

For my part, I find much to admire in a Japanese house, and some


things not to my comfort. The sitting posture on the floor is painful
until one gets accustomed to it; and, naturally, I find that our chairs
are painful to the Japanese, until they become accustomed to them. I
found the Japanese house in winter extremely cold and
uncomfortable; but I question whether their cold rooms in winter are
not more conducive to health than are our apartments with our
blistering stoves, hot furnaces or steam-heaters; and as to the odors
arising from the closet in certain country inns, who does not recall
similar offensive features in many of our country inns at home, with
the addition of slovenly yards and reeking piggeries? I question, too,
whether these odors are more injurious to the health than is the
stifling air from a damp and noisome cellar, which not only filters
through our floors, but is often served to us hot through scorching
furnaces. Whittier's description of the country house,—

The best room


Stifling with cellar-damp, shut from the air
In hot midsummer,—
is only too true of many of our American houses both in the country
and city.

Whether the Japanese house is right or wrong in its plan and


construction, it answers admirably the purposes for which it was
intended. A fire-proof building is certainly beyond the means of a
majority of this people, as, indeed, it is with us; and not being able to
build such a dwelling, they have from necessity gone to the other
extreme, and built a house whose very structure enables it to be
rapidly demolished in the path [pg 13] of a conflagration. Mats,
screen-partitions, and even the board ceilings can be quickly packed
up and carried away. The roof is rapidly denuded of its tiles and
boards, and the skeleton framework left makes but slow fuel for the
flames. The efforts of the firemen in checking the progress of a
conflagration consist mainly in tearing down these adjustable
structures; and in this connection it may be interesting to record the
curious fact that oftentimes at a fire the streams are turned, not
upon the flames, but upon the men engaged in tearing down the
building!

The improvements, however, that are imperatively demanded in


Japanese house-structure are such modifications as shall render the
building less inflammable. While these inflammable houses may be
well enough in the suburbs or in country villages, they are certainly
quite out of place in cities; and here, indeed, the authorities are
justified in imposing such restrictions as shall not bear too heavily
upon the people.

The Japanese should clearly understand that insuperable difficulties


are to be encountered in any attempt to modify their style of
dwellings, and that many of such proposed modifications are neither
judicious nor desirable. That slight changes for safety may be
effected, however, there can be no doubt. Through the agency of
science, means may be found by which outside woodwork may be
rendered less inflammable,—either by fire-proof paint or other
devices.
The mean path of Tokio conflagrations has been ingeniously worked
out by Professor Yamakawa, from data extending back two hundred
years; and in this path certain areas might be left open with
advantage. Fire-proof blocks in foreign style, such as now exist on
the Ginza, may be ultimately constructed in this path. Since the last
great conflagration, the Tokio authorities have specified certain
districts within which shingled roofs shall not be made; and where
such roofs existed, the authorities have compelled the substitution of
tin, zinc, or tiled roofs. Above all, [pg 14] let there be a
reorganization, under Government, of the present corrupt fire-
brigades. Such changes will certainly lead to good results; but as to
altering the present plan of house-building and present modes of
living, it is not only impracticable but well-nigh impossible. If such
changes are effected, then will perish many of the best features of
true Japanese art, which has been the surprise and admiration of
Western nations, and of which in the past they have been the
unwitting cause of the modification and degradation it has already
undergone.

Fig. 4.—Side Framing.


The frame-work of an ordinary Japanese dwelling is simple and
primitive in structure; it consists of a number of upright beams which
run from the ground to the transverse beams and inclines of the roof
above. The vertical framing is held together either by short strips
which are let in to appropriate notches in the uprights to which the
bamboo lathing is fixed, or by [pg 15] longer strips of wood which
pass through mortises in the uprights and are firmly keyed or pinned
into place (fig. 4). In larger houses these uprights are held in position
by a frame-work near the ground. There is no cellar or excavation
beneath the house, nor is there a continuous stone foundation as
with us. The uprights rest directly, and without attachment, upon
single uncut or rough-hewn stones, these in turn resting upon others
which have been solidly pounded into the earth by means of a huge
wooden maul worked by a number of men (fig. 5). In this way the
house is perched upon these stones, with the floor elevated at least a
foot and a half or two feet above the ground. In some cases the
space between the uprights is boarded up; this is generally seen in
Kioto houses. In others the wind has free play beneath; and while
this exposed condition renders the house much colder and more
uncomfortable in winter, the inmates are never troubled by the
noisome air of the cellar, which, as we have said, too often [pg 16]
infects our houses at home. Closed wooden fences of a more solid
character are elevated in this way; that is, the lower rail or sill of the
fence rests directly upon stones placed at intervals apart of six or
eight feet. The ravages of numerous ground-insects, as well as
larvae, and the excessive dampness of the ground at certain seasons
of the year, render this method of building a necessity.
Fig 5.—Pounding Down Foundation Stones.

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.

Fig. 6.—Foundation Stones.

Fig. 7.—Section of Framing.


Fig. 8.—Framing.

This cross-beam is often a straight unhewn stick of timber from


which the bark has been removed (fig. 49). Indeed, most of the
horizontal framing-timbers, as well as the rafters, [pg 18] are usually
unhewn,—the rafters often having the bark on, or perhaps being
accurately squared sticks; but in either case they are always visible as
they project from the sides of the house, and run out to support the
overhanging eaves. The larger beams and girders are but slightly
hewn; and it is not unusual to see irregular-shaped beams worked
into the construction of a frame, often for their quaint effects (fig. 7),
and in many cases as a matter of economy (fig. 39).
Fig. 9.—End-framing of Large Building.

For a narrow house, if the roof be a gable, a central upright at each


end of the building gives support to the ridge-pole from which the
rafters run to the eaves (fig. 8). If the building be wide, a transverse
beam traverses the end of the building on a level with the eaves,
supported at intervals by uprights from the ground; and upon this
short uprights rest, supporting [pg 19] another transverse beam
above, and often three or more tiers are carried nearly to the ridge.
Upon these supports rest the horizontal beams which run parallel
with the ridge-pole, and which are intended to give support to the
rafters (fig. 9).

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.

Fig 10.—Roof-frame of Large Building.

The roof, if it be of tile or thatch, represents a massive weight,—the


tiles being thick and quite heavy, and always bedded in a thick layer
of mud. The thatch, though not so heavy, often becomes so after a
long rain. The roof-framing consequently has oftentimes to support a
great weight; and though in its structure looking weak, or at least
primitive in design, yet experience must have taught the Japanese
carpenter that their methods were not only the simplest and most
economical, but that they answered all requirements. One is amazed
[pg 20] to see how many firemen can gather upon such a roof
without its yielding. I have seen massive house-roofs over two
hundred years old, and other frame structures of a larger size and of
far greater age, which presented no visible signs of weakness.
Indeed, it is a very unusual sight to see a broken-backed roof in
Japan.

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.

When the frame is mortised, the carpenter employs the most


elaborate methods of mortising, of which there are many different
formulas; yet I was informed by an American architect that their
ways had no advantage as regards strength over those employed by
our carpenters in doing the same work. There certainly seems to be
much unnecessary work about many of their framing-joints. This
same gentleman greatly admired the way in which the Japanese
carpenter used the adze, and regretted that more of this kind of work
was not done in America. In scarfing beams a common form of joint
is made, precisely similar to that made by our carpenters (fig. 4).
This joint is called a Samisen tsugi, it being similar to the joint in the
handle of a guitar-like instrument called a samisen.4

[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.

In the village of Naruge, in Yamato, I noticed in an old inn a diagonal


brace which made a pleasing ornamental feature to a solid frame-
work, upon which rested a ponderous supplementary roof, heavily
tiled. As the horizontal beams were supported by uprights beyond the
ends of the brackets, no additional strength was gained by these
braces in question, except as they might prevent fore and aft
displacement. They were placed here solely for their ornamental
appearance; or at least that was all the function they appeared to
perform (fig. 15).
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