Java 9 Cookbook - Mohamed Sanaulla - E-Book

Java 9 Cookbook E-Book

Mohamed Sanaulla

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

A definitive guide to learning the key concepts of modern application development in Java

About This Book

  • Learn the latest features of Java 9
  • Extend your Java knowledge and take your application to new levels by making it fast, secure, and scalable
  • Delve into the intricacies of Modular programming in Java 9

Who This Book Is For

The book is for intermediate to advanced Java programmers who want to make their applications fast, secure, and scalable.

What You Will Learn

  • Set up JDK and know the differences in the JDK 9 installation
  • Implement OO designs using classes and interfaces
  • Manage operating system processes
  • Understand the new modular JDK and modular programming
  • Create a modular application with clear dependencies
  • Build graphical user interfaces using JavaFX
  • Use the new HTTP Client API
  • Learn about the new diagnostic features in Java 9
  • See how to use the new jShell REPL tool
  • Execute ES6-compliant JavaScript code from your Java applications

In Detail

Java is an object-oriented programming language. It is one of the most widely accepted languages because of its design and programming features, particularly in its promise that you can write a program once and run it anywhere.

This cookbook offers a range of software development examples in simple and straightforward Java 9 code, providing step-by-step resources and time-saving methods to help you solve data problems efficiently. Starting with the installation of Java, each recipe addresses a specific problem, with a discussion that explains the solution and offers insight into how it works.

We cover major concepts such as Project Jigsaw and various tools that will enable you to modularize your applications. You will learn new features in the form of recipes that will make your applications modular, secure, and fast.

Style and approach

Each recipe in this book contains a series of complete instructions to perform a core task, plus an explanation of the purpose behind it. Similar methods or further refinements are included with each recipe to provide comprehensive guidance.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 643

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Java 9 Cookbook

 

 

 

 

 

 

 

 

 

 

Over 100 practical recipes to develop modern applications in Java

 

 

 

 

 

 

 

 

 

 

Mohamed Sanaulla
Nick Samoylov

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Java 9 Cookbook

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 authors, 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: August 2017

 

Production reference: 1180817

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78646-140-7

 

www.packtpub.com

Credits

Author

Mohamed Sanaulla

Nick Samoylov

Copy Editor

Muktikant Garimella

Reviewer

Aristides Villarreal Bravo

Project Coordinator

Ulhas Kambali

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto

Indexer

Rekha Nair

ContentDevelopmentEditor

Nikhil Borkar

Graphics

Abhinash Sahu

Technical Editor

Subhalaxmi Nadar

Production Coordinator

Melwyn Dsa

About the Authors

Mohamed Sanaulla is a software developer with over 7 years, experience in backend and full stack development. He is also one of the moderators on Code Ranch (formerly known as Java Ranch).

I would like to thank everyone who has helped me in the process of writing this book.

 

 

 

 

 

Nick Samoylov was born in Moscow, raised in Ukraine, and lived in the Crimea. He graduated as an engineer-physicist from Moscow Institute of Physics and Technologies, has worked as a theoretical physicist, and has learned programming as a tool for testing his mathematical models using FORTRAN and C++.

After the demise of the USSR, Nick created and successfully ran a software company, but was forced to close it under the pressure of governmental and criminal rackets. In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado since then.

Nick adopted Java in 1997 and used it for working as a software developer-contractor for a variety of companies, including BEA Systems, Warner Telecom, and Boeing. For Boeing, he and his wife, also a Java programmer, developed a system of loading application data to the airplane via the internet.

Nick's current projects are related to machine learning and developing a highly scalable system of microservices using non-blocking reactive technologies, including Vert.x, RxJava, and RESTful webservices on Linux deployed in a cloud.

Nick and Luda have two daughters who graduated from Harvard and Tufts universities, respectively. One has also received a doctoral degree from Brown University and now works as a professor in the University of California in Chico. The other daughter is an executive director of the investment bank, JPMorgan, in Madrid, Spain.

In his free time, Nick likes to read (mostly non-fiction), write (fiction novels and blogs), and hike the Rocky Mountains.

About the Reviewer

Aristides Villarreal Bravo is a Java developer, a member of the NetBeans Dream Team, and a Java User Groups leader. He lives in Panama. He has organized and participated in various conferences and seminars related to Java, JavaEE, NetBeans, the NetBeans platform, free software, and mobile devices. He is the author of jmoordb and tutorials, and he blogs about Java, NetBeans, and web development.

Aristides has participated in several interviews on sites about topics such as NetBeans, NetBeans DZone, and JavaHispano. He is a developer of plugins for NetBeans. He is the CEO of Javscaz Software Developers. He has also worked on Developers of jmoordb.

 

I would like to thank my mother, father, and all family and friends.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com. 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/1786461404.

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!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Installation and a Sneak Peek into Java 9

Introduction

Installing JDK 9 on Windows and setting up the PATH variable

How to do it...

Installing JDK 9 on Linux (Ubuntu, x64) and configuring the PATH variable

How to do it...

Compiling and running a Java application

Getting ready

How to do it...

New features in Java 9

How to do it...

JEP 102 -- Process API updates

JEP 110 -- HTTP/2 client

JEP 213 -- milling project coin

JEP 222: jshell -- the Java shell (Read-Eval-Print Loop)

JEP 238 -- multi-release JAR files

JEP 266 -- more concurrency updates

Project Jigsaw

There's more...

Using new tools in JDK 9

Getting ready

How to do it...

jdeprscan

jdeps

jlink

jmod

JShell

Comparing JDK 8 and JDK 9

Getting ready

How to do it...

See also

Fast Track to OOP - Classes and Interfaces

Introduction

Implementing object-oriented design using classes

Getting ready

How to do it...

How it works...

There's more...

See also

Using inner classes

Getting ready

How to do it...

How it works...

There's more...

See also

Using inheritance and composition to make the design extensible

Getting ready

How to do it...

How it works...

Composition makes the design more extensible

See also

Coding to an interface

Getting ready

How to do it...

How it works...

There's more...

See also

Creating interfaces with default and static methods

Getting ready

How to do it...

How it works...

See also

Creating interfaces with private methods

Getting ready

How to do it...

How it works...

There's more...

See also

Using enums to represent constant entities

Getting ready

How to do it...

How it works...

There's more...

Using the @Deprecated annotation to deprecate APIs

Getting ready

How to do it...

How it works...

There's more...

Using HTML5 in Javadocs

Getting ready

How to do it...

Modular Programming

Introduction

Using jdeps to find dependencies in a Java application

Getting ready

How to do it...

How it works...

There's more...

Creating a simple modular application

Getting ready

How to do it...

How it works...

See also

Creating a modular JAR

Getting ready

How to do it...

Using a module JAR with pre-JDK 9 applications

Getting ready

How to do it...

See also

Bottom-up migration

Getting ready

How to do it...

Modularizing banking.util.jar

Modularizing math.util.jar

Modularizing calculator.jar

How it works...

Top-down migration

Getting ready

How to do it...

Modularizing the calculator

Modularizing banking.util

Modularizing math.util

Using services to create loose coupling between consumer and provider modules

Getting ready

How to do it...

Creating a custom modular runtime image using jlink

Getting ready

How to do it...

Compiling for older platform versions

Getting ready

How to do it...

How it works...

Creating multirelease JARs

How to do it...

How it works...

Using Maven to develop a modular application

Getting ready

How to do it...

Going Functional

Introduction

Understanding and creating a functional interface

Getting ready

How to do it...

How it works...

There's more...

See also

Understanding lambda expressions

Getting ready

How to do it...

How it works...

There's more...

See also

Using method references

Getting ready

How to do it...

There's more...

See also

Creating and invoking lambda-friendly APIs

Getting ready

How it works...

There's more...

See also

Leveraging lambda expressions in your programs

Getting ready

How to do it...

There's more...

See also

Stream Operations and Pipelines

Introduction

Using the new factory methods to create collection objects

Getting ready

How to do it...

There's more...

See also

Creating and operating on streams

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an operation pipeline on streams

Getting ready

How to do it...

There's more...

See also

Parallel computations on streams

Getting ready

How to do it...

See also

Database Programming

Introduction

Connecting to a database using JDBC

How to do it...

How it works...

There's more...

See also

Setting up the tables required for DB interactions

Getting ready

How it works...

There's more...

See also

Performing CRUD operations

Getting ready

How to do it...

There's more...

See also

Using prepared statements

Getting ready

How to do it...

There's more...

See also

Using transactions

Getting ready

How to do it...

There's more...

Working with large objects

Getting ready

How to do it...

There's more...

Executing stored procedures

Getting ready

How to do it...

There's more...

Concurrent and Multithreaded Programming

Introduction

Using the basic element of concurrency - thread

Getting ready

How to do it...

There's more...

See also

Different synchronization approaches

Getting ready

How to do it...

There's more...

 See also

Immutability as a means to achieve concurrency

Getting ready

How to do it...

There's more...

See also

Using concurrent collections

Getting ready

How to do it...

How it works...

See also

Using the executor service to execute async tasks

Getting ready

How to do it...

How it works...

There's more...

See also

Using fork/join to implement divide-and-conquer

Getting ready

How to do it...

Using flow to implement the publish-subscribe pattern

Getting ready

How to do it...

Better Management of the OS Process

Introduction

Spawning a new process

Getting ready

How to do it...

How it works...

Redirecting the process output and error streams to file

Getting ready

How to do it...

There is more...

Changing the working directory of a subprocess

Getting ready

How to do it...

How it works...

Setting the environment variable for a subprocess

How to do it...

How it works...

Running shell scripts

Getting ready

How to do it...

How it works...

Obtaining the process information of the current JVM

How to do it...

How it works...

Obtaining the process information of the spawned process

Getting ready

How to do it...

Managing the spawned process

How to do it...

Enumerating live processes in the system

How to do it...

Connecting multiple processes using pipe

Getting ready

How to do it...

How it works...

Managing subprocesses

Getting ready

How to do it...

How it works...

GUI Programming Using JavaFX

Introduction

Creating a GUI using JavaFX controls

 Getting ready

How to do it...

How it works...

Using the FXML markup to create a GUI

Getting ready

How to do it...

How it works...

See also 

Using CSS to style elements in JavaFX

Getting ready

How to do it...

How it works...

Creating a bar chart

Getting ready

How to do it...

How it works...

See also

Creating a pie chart

Getting ready

How to do it...

How it works...

Creating a line chart

Getting ready

How to do it...

How it works...

See also

Creating an area chart

Getting ready

How to do it...

How it works...

See also

Creating a bubble chart

Getting ready

How to do it...

How it works...

See also

Creating a scatter chart

Getting ready

How to do it...

How it works...

See also

Embedding HTML in an application

Getting ready

How to do it...

How it works...

There's more...

Embedding media in an application

Getting ready

How to do it...

How it works...

There's more...

Adding effects to controls

How to do it...

How it works...

There's more...

Using the new TIFF I/O API to read TIFF images

Getting ready

How to do it...

RESTful Web Services Using Spring Boot

Introduction

Creating a simple Spring Boot application

Getting ready

How to do it...

How it works...

Interacting with the database

Getting ready

Installing MySQL tools

Creating a sample database

Creating a person table

Populating sample data

How to do it...

How it works...

Creating a RESTful web service

Getting ready

How to do it...

How it works...

Creating multiple profiles for Spring Boot

Getting ready

How to do it...

How it works...

There's more...

Deploying RESTful web services to Heroku

Getting ready 

Setting up a Heroku account

Creating a new app from the UI

Creating a new app from the CLI

How to do it...

There's more...

Containerizing the RESTful web service using Docker

Getting ready

How to do it...

How it works...

Networking

Introduction

Making an HTTP GET request

How to do it...

How it works...

Making an HTTP POST request

How to do it...

Making an HTTP request for a protected resource

How to do it...

How it works...

Making an asynchronous HTTP request

How to do it...

Making an HTTP request using Apache HttpClient

Getting ready

How to do it...

There is more...

Making an HTTP request using the Unirest HTTP client library

Getting ready

How to do it...

There's more...

Memory Management and Debugging

Introduction

Understanding the G1 garbage collector

Getting ready

How to do it...

How it works...

See also

Unified logging for JVM

Getting ready

How to do it...

See also

Using the new diagnostic commands for the JVM

How to do it...

How it works...

See also

Try with resources for better resource handling

How to do it...

How it works...

See also

Stack walking for improved debugging

Getting ready

How to do it...

How it works...

See also

Some best practices for better memory usage

How it  works...

See also

The Read-Evaluate-Print Loop (REPL) Using JShell

Introduction

Getting familiar with REPL

Getting ready

How to do it...

How it works...

Navigating JShell and its commands

How to do it...

Evaluating code snippets

How to do it...

There's more...

Object-oriented programming in JShell

How to do it...

Saving and restoring the JShell command history

How to do it...

Using the JShell Java API

How to do it...

How it works...

Scripting Using Oracle Nashorn

Introduction

Using the jjs command-line tool

Getting ready

How to do it...

There's more...

Embedding the Oracle Nashorn engine

Getting ready

How to do it...

Invoking Java from Oracle Nashorn

How to do it...

How it works...

There's more...

Using the ES6 features implemented in Oracle Nashorn

How to do it... 

Testing

Introduction

Unit testing of an API using JUnit

Getting ready

How to do it...

How it works...

See also

Unit testing by mocking dependencies

Getting ready

How to do it...

How it works...

There's more...

See also

Using fixtures to populate data for testing

How to do it...

How it works...

See also

Behavioral testing

Getting ready

How to do it...

How it works...

Preface

This cookbook offers a range of software development examples in simple and straightforward Java 9 code, providing step-by-step resources and time-saving methods to help you solve data problems efficiently. Starting with the installation of Java, each recipe addresses a specific problem, with a discussion that explains the solution, and offers insight into how it works. We cover major concepts about the core programming language as well as common tasks to build a wide variety of software. You will learn new features in the form of recipes, to make your application modular, secure, and fast.

What this book covers

Chapter 1, Installation and Sneak Peek into Java 9, helps you to set up the development environment for running your Java programs and gives a brief overview of the new features and tools in Java 9

Chapter 2, Fast Track to OOP - Classes and Interfaces, covers object-oriented programming principles and design solutions, including inner classes, inheritance, composition, interfaces, enumerations, and the Java 9 changes to Javadocs.

Chapter 3, Modular Programming, introduces jigsaw as a major feature and a huge leap for the Java ecosystem. This chapter demonstrates how to use tools, such as jdeps and jlink, to create simple modular applications, and related artifacts such as modular JARs, and finally how to modularize your pre-Java 9 applications.

Chapter 4, Going Functional, introduces a programming paradigm called functional programming and its applicability in Java 9. Topics covered include functional interfaces, lambda expressions, and lambda-friendly APIs.

Chapter 5, Stream Operations and Pipelines, shows how to leverage streams and chain multiple operations on a collection to create a pipeline, use factory methods to create collection objects, create and operate on streams, and create an operation pipeline on streams, including parallel computations.

Chapter 6, Database Programming, covers both basic and commonly used interactions between a Java application and a database, right from connecting to the database and performing CRUD operations to creating transactions, storing procedures, and working with large objects.

Chapter 7, Concurrent and Multithreaded Programming, presents different ways of incorporating concurrency and some best practices, such as synchronization and immutability. We will also discuss the implementation of some commonly used patterns, such as divide-conquer and publish-subscribe, using the constructs provided by Java.

Chapter 8, Better Management of the OS Process, elaborates on the new API enhancements around the Process API.

Chapter 9, GUI Programming Using JavaFX, shows how to get started with creating JavaFX applications, leverage CSS styling into your applications, build a GUI in a declarative way using FXML, and use the graph, media, and browser components of JavaFX.

Chapter 10, RESTful Webservices Using Spring Boot, deals with creating simple RESTful webservices using Spring boot, deploying them to Heroku, and finally dockerizing Spring boot-based RESTful webservice applications.

Chapter 11, Networking, shows you how to use different HTTP client API libraries, namely the API provided in Java 9 as an incubator module, the Apache HTTP client, and the Unirest HTTP client API.

Chapter 12, Memory Management and Debugging, explores managing the memory of a Java application, including an introduction to the garbage collection algorithm used in Java 9, and some new features, which help in advanced application diagnostics. We'll also show how to manage resources by using the new try-with-resources construct and the new stack walking API.

Chapter 13, The Read-Evaluate-Print Loop (REPL) Using JShell, shows you how to work with the new REPL tool and JShell, provided as part of the JDK.

Chapter 14, Scripting Using Oracle Nashorn, shows how to interoperate between JavaScript and Java using the Oracle Nashorn JavaScript engine and how to use the jjs command-line tool to run JavaScript. It also explores Oracle Nashorn's support for the new ECMAScript 6.

Chapter 15, Testing, explains how to unit-test your APIs before they are integrated with other components, including stubbing dependencies with some dummy data and mocking dependencies. We will also show you how to write fixtures to populate the test data and then how to test your application behavior by integrating different APIs and testing them.

What you need for this book

To run the code examples, you will need a computer with 2GB RAM at least, 10GB free disk space, and Windows or Linux OS. The following software/libraries are required:

JDK 9 (for all chapters)

PostgreSQL 9.4 DB (for

Chapter 6

,

Database Programming

)

Junit 4.12 (for

Chapter 15

,

Testing

)

Mockito 2.7.13 (for

Chapter 15

,

Testing

)

Maven 3.5.0 (for

Chapter 3

,

Modular Programming

)

MySQL 5.7.19 DB (for

Chapter 10

,

RESTful Webservices Using Spring Boot

)

Heroku CLI (for

Chapter 10

,

RESTful Webservices Using Spring Boot

)

Docker (for

Chapter 10

,

RESTful Webservices Using Spring Boot

)

Who this book is for

The book is for intermediate to advanced Java programmers who want to make their applications fast, secure, and scalable.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also). To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "When run, it produces the same value as with an object of the Vehicle class." A block of code is set as follows:

module newfeatures{ requires jdk.incubator.httpclient;}

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

$> vim ~/.bash_aliases

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

Warnings or important notes appear 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 disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. 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 at 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:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

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-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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.

Installation and a Sneak Peek into Java 9

In this chapter, we will cover the following recipes: 

Installing JDK 9 on Windows and setting up the PATH variable

Installing JDK 9 on Linux (Ubuntu, x64) and configuring the PATH variable

Compiling and running a Java application

New features in Java 9

Using new tools in JDK 9

Comparing JDK 8 with JDK 9

Introduction

Every quest for learning a programming language begins with setting up the environment to experiment our learning. Keeping in sync with this philosophy, in this chapter, we will show you how to set up your development environment and then run a simple modular application to test our installation. After that, we'll give you an introduction to the new features and tools in JDK 9. Then, we'll end the chapter with a comparison between the JDK 8 and JDK 9 installations.

Installing JDK 9 on Windows and setting up the PATH variable

In this recipe, we will look at installing JDK on Windows and how to set up the PATH variable to be able to access the Java executables (such as javac, java, and jar, among others) from anywhere within the command shell.

How to do it...

Visit https://jdk9.java.net/download/ and accept the early adopter license agreement, which looks like this:

After accepting the license, you will get a grid of the available JDK bundles based on the OS and architecture (32/64 bit), as shown here:

 

Click to download the relevant JDK executable (

.exe

) for your Windows platform.

Run the JDK executable (

.exe

) and follow the onscreen instructions to install JDK on your system.

If you have chosen all the defaults during the installation, you will find JDK installed in 

C:/Program Files/Java

 for 64 bit and

C:/Program Files (x86)/Java

for 32 bit.

Now that we have finished installing JDK, let's see how we can set the PATH variable.

The tools provided with JDK, namely javac, java, jconsole, and jlink, among others, are available in the bin directory of your JDK installation. There are two ways you could run these tools from the command prompt:

Navigate to the directory where the tools are installed and then run them, as follows: 

cd "C:\Program Files\Java\jdk-9\bin" javac -version

Export the path to the directory so that the tools are available from any directory in the command prompt. To achieve this, we have to add the path to the JDK tools in the

PATH

environment variable. The command prompt will search for the relevant tool in all the locations declared in the

PATH

environment variable. 

Let's see how you can add the JDK bin directory to the PATH variable:

Right click on

My Computer

and then click on

Properties

. You will see your system information. Search for

Advanced system settings

 and click on it to get a window, as shown in the following screenshot:

 

Click on

Environment Variables

to view the variables defined in your system. You will see that there are quite a few environment variables already defined, as shown in the following screenshot (the variables will differ across systems; in the following screenshot, there are a few predefined variables and a few variables added by me): The variables defined under

System variables

are available across all the users of the system, and those defined under

User variables for sanaulla

are available only to the user, 

sanaulla

.

Click on

New

under

User variables for <your username>

 to add a new variable, with the name 

JAVA_HOME

, and its value as the location of the JDK 9 installation. For example, it would be 

C:/Program Files/Java/jdk-9

(for 64 bit) or 

C:/Program Files (x86)/Java/jdk-9

(for 32 bit):

The next step is to update the

PATH

environment variable with the location of the bin directory of your JDK installation (defined in the 

JAVA_HOME

environment variable). If you already see the 

PATH

variable defined in the list, then you need to select that variable and click on

Edit

. If the 

PATH

variable is not seen, then click on

New

.

Any of the actions in the previous step will give you a popup, as shown in the following screenshot (on Windows 10):

The following image shows the other Windows versions:

You can either click on

New

in the first picture and insert the value, 

%JAVA_HOME%/bin

, or you can append the value against the

Variable value

field by adding

; %JAVA_HOME%/bin

. The semicolon (

;

) in Windows is used to separate multiple values for a given variable name.

After setting the values, open the command prompt and then run

javac -version

, and you should be able to see

javac 9-ea

as the output. If you don't see it, then it means that the bin directory of your JDK installation has not been correctly added to the

PATH

variable.

Installing JDK 9 on Linux (Ubuntu, x64) and configuring the PATH variable

In this recipe, we will look at installing JDK on Linux (Ubuntu, x64) and also how to configure the PATH variable to make the JDK tools (such as javac, java, jar, and others) available from any location within the terminal.

How to do it...

Follow the Steps 1 and 2 of the

Installing JDK 9 on Windows and setting up the PATH variable

 recipe to reach the downloads page.

Copy the download link (

tar.gz

) for the JDK for the Linux x64 platform from the downloads page. 

Download the JDK by using

$> wget <copied link>

, for example,

$> wget http://download.java.net/java/jdk9/archive/180/binaries/jdk-9+180_linux-x64_bin.tar.gz

.

Once the download completes, you should have the relevant JDK available, for example,

jdk-9+180_linux-x64_bin.tar.gz

. You can list the contents by using

$> tar -tf jdk-9+180_linux-x64_bin.tar.gz

. You can even pipe it to

more

to paginate the output:

$> tar -tf jdk-9+180_linux-x64_bin.tar.gz | more

.

Extract the contents of the

tar.gz

file under

/usr/lib

by using

$> tar -xvzf jdk-9+180_linux-x64_bin.tar.gz -C /usr/lib

. This will extract the contents into a directory, 

/usr/lib/jdk-9

. You can then list the contents of JDK 9 by using

$> ls /usr/lib/jdk-9

.

 

Update the

JAVA_HOME

and

PATH

variables by editing the 

.bash_aliases

file in your Linux home directory: 

$> vim ~/.bash_aliases export JAVA_HOME=/usr/lib/jdk-9 export PATH=$PATH:$JAVA_HOME/bin

Source the .bashrc file to apply the new aliases:

$> source ~/.bashrc $> echo $JAVA_HOME /usr/lib/jdk-9 $>javac -version javac 9 $> java -version java version "9"

Java(TM) SE Runtime Environment (build 9+180)

Java HotSpot(TM) 64-Bit Server VM (build 9+180, mixed mode)

All the examples in this book are run against JDK installed on Linux (Ubuntu, x64), except for places where we have specifically mentioned that these are run on Windows. We have tried to provide run scripts for both platforms.The recipes on JavaFX are completely executed on Windows. 

Compiling and running a Java application

In this recipe, we will write a very simple modular Hello world program to test our JDK installation. This simple example prints Hello world in XML; after all it's the world of web services.

Getting ready

You should have JDK installed and the PATH variable updated to point to the JDK installation.

New features in Java 9

The release of Java 9 is a milestone in the Java ecosystem. The much awaited modular framework developed under Project Jigsaw will be part of this Java SE release. Another major feature in this is the JShell tool, which is an REPL tool for Java. Apart from this, there are other important API changes and JVM-level changes to improve the performance and debuggability of the JVM. In a blog post (https://blogs.oracle.com/java/jdk-9-categories), Yolande Poirier categorizes JDK 9 features into the following: 

Behind the scenes

New functionality

Specialized

New standards

Housekeeping

Gone

The same blog post has summarized the preceding categorization into the following image:

In this recipe, we will discuss a few important features of JDK 9 and, wherever possible, also show a small code snippet of that feature in action. Every new feature in JDK is introduced by means of JDK Enhancement Proposals, also called JEPs. More information about the different JEPs part of JDK 9 and the release schedule of JDK 9 can be found on the official project page:http://openjdk.java.net/projects/jdk9/. 

How to do it...

We have picked a few features, which we feel are amazing and worth knowing about. In the following few sections, we'll briefly introduce you to those features.

JEP 222: jshell -- the Java shell (Read-Eval-Print Loop)

You must have seen languages, such as Ruby, Scala, Groovy, Clojure, and others shipping with a tool, which is often called REPL (Read-Eval-Print-Loop). This REPL tool is extremely useful in trying out the language features. For example, in Scala, we can write a simple Hello World program as scala> println("Hello World");

Some of the advantages of the JShell REPL are as follows:

Help language learners to quickly try out the language features

Help experienced developers to quickly prototype and experiment before adopting it in their main code base

Java developers can now boast of an REPL

Let's quickly spawn our command prompts/terminals and run the JShell command, as shown in the following image:

There is a lot more we can do, but we will keep that for Chapter 13, The Read-Evaluate-Print Loop (REPL) Using JShell.

JEP 238 -- multi-release JAR files

As of now, JAR files can contain classes that can only run on the Java version they were compiled for. To leverage the new features of the Java platform on newer versions, the library developers have to release a newer version of their library. Soon, there will be multiple versions of the library being maintained by the developers, which can be a nightmare. To overcome this limitation, the new feature of multirelease JAR files allows developers to build JAR files with different versions of class files for different Java versions. The following example makes it more clear. 

Here is an illustration of the current JAR files:

jar root - A.class - B.class - C.class

Here is how multirelease JAR files look:

jar root - A.class - B.class - C.class - META-INF - versions - 9 - A.class - 10 - B.class

In the preceding illustration, the JAR files support class files for two Java versions--9 and 10. So, when the earlier JAR is executed on Java 9, the A.class under the versions- 9 folder is picked for execution. On a platform that doesn't support multirelease JAR files, the classes under the versions directory are never used. So, if you run the multirelease JAR file on Java 8, it's as good as running a simple JAR file.

JEP 266 -- more concurrency updates

In this update, a new class, java.util.concurrent.Flow, has been introduced, which has nested interfaces supporting the implementation of a publish-subscribe framework. The publish-subscribe framework enables developers to build components that can asynchronously consume a live stream of data by setting up publishers that produce the data and subscribers that consume the data via subscription, which manages them. The four new interfaces are as follows:

java.util.concurrent.Flow.Publisher

java.util.concurrent.Flow.

Subscriber

java.util.concurrent.Flow.

Subscription

java.util.concurrent.Flow.

Processor

(which acts as both

Publisher

and

Subscriber

).

Project Jigsaw

The main aim of this project is to introduce the concept of modularity; support for creating modules in Java and then apply the same to the JDK; that is, modularize the JDK. Some of the benefits of modularity are as follows:

Stronger encapsulation: The modules can access only those parts of the module that have been made available for use. So, the public classes in a package are not public unless the package is explicitly exported in the module info file. This encapsulation cannot be broken by using reflection (except in cases where the module is an open module or specific packages in the module have been made open).

Clear dependencies: Modules must declare which other modules they would be using via the

requires

clause.

Combining modules to create a smaller runtime, which can be easily scaled to smaller computing devices.

Make the applications more reliable by eliminating runtime errors. For example, you must have experienced your application failing during runtime due to missing classes, resulting in

ClassNotFoundException

.

There are various JEPs, which are part of this project, as follows:

JEP 200 - modular JDK

: This applies the Java platform module system to modularize the JDK  into a set of modules that can be combined at compile time, build time, or runtime.

JEP 201 - modular source code

: This modularizes the JDK source code into modules and enhances the build tools to compile the modules.

JEP 220 - modular runtime images

: This restructures the JDK and JRE runtime images to accommodate modules and to improve performance, security, and maintainability.

JEP 260 - encapsulate most internal APIs

: This allows a lot of internal APIs to be accessed directly or via reflection. Accessing internal APIs that are bound to change is quite risky. To prevent its use, they are being encapsulated into modules and only those internal APIs that are widely used are being made available until a proper API is in its place.

JEP 261 - module system

: This implements the module system Java specification by changing the Java programming language, JVM, and other standard APIs (

http://cr.openjdk.java.net/~mr/jigsaw/spec/lang-vm.html

). This includes the introduction of a new construct called module, 

{ }

, with its supported keywords, such as

requires

,

exports

,

opens

, and

uses

JEP 282: jlink, the Java linker

: This allows packaging modules and their dependencies into smaller run times. 

More details about Project Jigsaw can be found from the Project Jigsaw homepage (http://openjdk.java.net/projects/jigsaw/).

There's more...

There are quite a few features listed that are significant for developers, and we thought of grouping them together for your benefit:

Enhance the Javadoc tool to generate HTML 5 output and the generated Javadoc should support the local search for classes and other elements. 

Make G1 as the default garbage collector and remove GC combinations that have been deprecated in Java 8. G1 is the new garbage collector (which has been in existence since Java SE 7), which focuses on reducing the pause times of the garbage collection activity. These pause times are very critical to latency-critical applications and, hence, such applications are going towards adopting the new garbage collector.

Changing the internal representation of

String

to make use of a byte array rather than a character array. In a character array, each array element is 2 bytes, and it was observed that a majority of strings use 1 byte. This resulted in wasteful allocation. The new representation would also introduce a flag to indicate the type of encoding used. 

The new stackwalking API to support navigating the stack trace, which will help to do much more than just print the stack trace.

Allow the image I/O plugin to support the TIFF image format.

Using new tools in JDK 9

There are a few new command-line tools introduced in JDK 9 to support new features. We will give you a quick overview of these tools and the same will be explained with recipes of their own in the later chapters.

Getting ready

You should have JDK 9 installed and the PATH environment variable updated to add the path to the bin directory of your JDK installation. Also, you need to have tried out HelloWorldXml explained in the recipe, Compiling and running a Java application.

How to do it...

We will look at a few interesting new command-line tools introduced.

jdeps

This tool analyses your code base specified by the path to the .class file, directory, or JAR, lists the package-wise dependency of your application, and also lists the JDK module in which the package exists. This helps in identifying the JDK modules that the application depends on and is the first step in migrating to modular applications.

We can run the tool on our HelloWorldXml example written earlier and see what jdeps provides:

$> jdeps mods/com.packt/ com.packt -> java.base com.packt -> java.xml.bind com.packt -> java.io java.base com.packt -> java.lang java.base com.packt -> javax.xml.bind java.xml.bind com.packt -> javax.xml.bind.annotation java.xml.bind

jlink

This tool is used to select modules and create a smaller runtime image with the selected modules. For example, we can create a runtime image by adding the com.packt modules created in our HelloWorldXml example:

$> jlink --module-path mods/:$JAVA_HOME/jmods/ --add-modules com.packt --output img

Looking at the contents of the img folder, we should find that it has the bin, conf, include, and lib directories. We will learn more about jlink under Chapter 3, Modular Programming.

jmod

JMOD is a new format for packaging your modules. This format allows including native code, configuration files, and other data that do not fit into JAR files. The JDK modules have been packaged as JMOD files.

The jmod command-line tool allows create, list, describe, and hash JMOD files:

create

: This is used to create a new

jmod

file

list

:  This is used to list the contents of a

jmod

file

describe

: This is used to describe module details

hash

: This is used to record hashes of tied modules

JShell

This tool has been briefly explained earlier, under the title, JEP 222: jshell - the Java shell (Read-Eval-Print Loop)

Comparing JDK 8 and JDK 9

Due to the application of a modular system to JDK under Project Jigsaw, there have been a few changes in the JDK directory structure installed in your systems. In addition to these, there were a few changes undertaken to fix the JDK installation structure, which dates back to the times of Java 1.2. This has been deemed to be a golden opportunity by the JDK team to fix the issues with the JDK directory structure.

Getting ready

To see the difference in the JDK 9 directory structure, you will need to install a pre-JDK 9 version. We have chosen to use JDK 8 to compare with JDK 9. So, go ahead and install JDK 8 before you proceed further. 

How to do it...

We did a side-by-side comparison of both the JDK installation directories as shown in the following:

Following are our observations from the preceding comparison:

The

jre

directory has been completely removed and has been replaced by

jmods

 and 

conf

. The

jmods

directory contains the runtime images of the JDK modules, the

conf

directory contains configuration and property files, which were earlier under the 

jre

directory. 

The contents of

jrebin

and

jrelib

have been moved to the lib and bin directories of JDK installation.

See also

Refer to the following recipe of this chapter:

Using new tools in JDK 9

Fast Track to OOP - Classes and Interfaces

In this chapter, we will cover the following recipes:

Implementing object-oriented design using classes

Using inner classes

Using inheritance and composition to make the design extensible

Coding to an interface

Creating interfaces with default and static methods

Creating interfaces with private methods

Using enums to represent constant entities

Using the @Deprecated annotation to deprecate APIs

Using HTML5 in Javadocs

Introduction

This chapter gives you a quick introduction to the components of OOP and covers the new enhancements in these components in Java 8 and Java 9. We will also try to cover a few good object-oriented design (OOD) practices wherever applicable.

Throughout the recipes, we will use the new (introduced in Java 8 and Java 9) enhancements, define and demonstrate the concepts of OOD using specific code examples, and present new capabilities for better code documentation.

One can spend many hours reading articles and practical advice on OOD in books and on the Internet. Some of this activity can be beneficial for some people. But, in our experience, the fastest way to get hold of OOD is to try its principles early in your own code. This is exactly the goal of this chapter: to give you a chance to see and use the OOD principles so that the formal definition makes sense immediately.

One of the main criteria of well-written code is its clarity of expressing its intent. A well-motivated and clear design helps achieve this. The code is run by a computer, but it is maintained and extended by humans. Keeping this in mind will assure longevity of the code written by you and perhaps even a few thanks and mentions with appreciation. 

In this chapter, you will learn how to use the five basic OOD concepts:

Object/Class - Keeping data and procedures together

Encapsulation - Hiding data and/or procedures

Inheritance - Extending another class data and/or procedures

Interface - Deferring the implementation and coding for a type

Polymorphism - Using the base class type for all its extensions when a parent class reference is used to refer to a child class object

These concepts will be defined and demonstrated in the code snippets presented in this chapter. If you search the Internet, you may notice that many other concepts and additions to them can be derived from the five points we just discussed.

Although the following text does not require prior knowledge of OOD, some experience of writing code in Java would be beneficial. The code samples are fully functional and compatible with Java 9. For better understanding, we recommend that you try to run the presented examples.

We also encourage you to adapt the tips and recommendations in this chapter to your needs in the context of your team experience. Consider sharing your new-found knowledge with your colleagues and discuss how the described principles can be applied to your domain, for your current project.

Implementing object-oriented design using classes

In this recipe, you will learn about the first two OOD concepts: object/class and encapsulation.

Getting ready

The term object usually refers to the coupling of data and procedures that can be applied to these data. Neither data, nor procedures are required, but one of them is--and, typically, both are--always present. The data are called object properties, while procedures are called methods. Properties capture the state of the object. Methods describe objects' behavior. Every object has a type, which is defined by its class (see the following). An object also is said to be an instance of a class.

The term class is a collection of the definitions of properties and methods that will be present in each of its instances--the objects created based on this class. Encapsulation is the hiding of object properties and methods that should not be accessible by other objects.

Encapsulation is achieved by the Java keywords private or protected in the declaration of properties and methods.