Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Modular Programming in Java 9
Modular Programming in Java 9

Modular Programming in Java 9: Build large scale applications using Java modularity and Project Jigsaw

eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Modular Programming in Java 9

Creating Your First Java Module

In the previous chapter, we took a detailed look at the problems associated with modularizing Java code pre-Java 9, as well as the new module construct in Java 9 and Project Jigsaw. Before we examine how Java modularity solves these problems, you'll need to first understand what a Java module looks like. In this chapter, you'll create your first Java 9 module and learn what it takes to build and execute code in a Java module. Here are the top-level topics you'll be learning in this chapter:

  • Setting up the JDK with Java 9
  • Creating a new Java 9 module
  • Defining a module (using module-info.java)
  • Compiling and executing a module
  • Handling possible errors

You'll be building a sample Java 9 application throughout this book as you learn the different concepts related to modularity. The application you'll build is an address book...

Setting up the JDK

In order to write Java 9 code, you'll first need to download and install the Java 9 SDK (referred to as the Java Development Kit or JDK). In this book, we'll be using the OpenJDK build available at http://jdk.java.net/9/. When you navigate to the URL, you'll see a list of available downloads based on the platform you are using, as shown here:

Make sure you choose the download for your platform in the JDK column, not the JRE column. After accepting the license agreement, you should be able to download an installer for your platform. Run the installer and choose the defaults; after this, you should have JDK 9 installed in your machine:

After the installation is complete, it's a good idea to verify that the JDK installation and configuration process completed successfully. You do that by opening a Command Prompt or terminal window. Type the...

Switching between JDKs

Once you've installed a newer version of the JDK with an earlier version already installed, it is possible to switch what the currently selected version is.

On macOS and Linux, you do this by switching the value of JAVA_HOME

The following command switches the current Java platform to Java 8:

$ export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

To switch to Java 9, use the following command:

$ export JAVA_HOME=$(/usr/libexec/java_home -v 9)
With this command, you are passing the Java version of choice to the -v parameter. But, note that the format is different between Java 8 and 9. With Java 8, the version string is 1.8. With Java 9, the version string is just 9. Traditionally, Java has been using the 1.X version format, for example, Java version 7 had the version string 1.7. This is being changed from Java 9 onward. The idea is that subsequent releases...

Setting up the NetBeans IDE

In order to write and follow the code in this book, you don't have to use any integrated development environments (IDEs). This book will cover writing, compiling, and executing code manually using the command line. You can write code using a text editor of your choice. The code samples accompanying this book also work with the steps and commands showcased in this book.

You could also follow along with an IDE. At the time of writing, NetBeans and IntelliJ Idea has growing support for Java modular projects, with Eclipse support under development. This chapter outlines the steps to create a modular project in NetBeans, should you choose to use the NetBeans IDE. To set it up, in addition to following the steps to set up Java, make sure you install the latest version of NetBeans with Java 9 module support by going to https://netbeans.org/downloads/...

Java 9 modules

When writing an application in Java 9, you are ideally creating a modular application. It's important to note that a modular Java application isn't just a regular Java application (like those we've been building all these years) with just an extra module feature thrown in. It actually calls for a completely new way of thinking about writing and structuring your code base. Before we get into creating Java 9 modules, let's do a quick recap of the traditional Java code structure pre-Java 9.

Traditional Java code structure

Traditionally, writing a Java application starts with creating one or more source directories. These are special directories that serve two purposes--firstly, they act as root...

Creating a module using NetBeans

Now that you've learned how to create, compile, and execute a module using the Command Prompt, let's see how to do the same thing using the NetBeans IDE:

  1. Create a new project in the NetBeans IDE by clicking in the toolbar or, through the menu File | New Project, you'll see a New Project overlay with a new option in the Java category--Java Modular Project:
  1. Select that and click Next. In the next dialog, you can specify the name of your project (I chose addressbookviewer) and the location of your project and click Finish:
  1. Once the new project is loaded onto your IDE, you can right-click on the name of the project in the Projects tab and choose the option to create a new module:
  1. In the New Module dialog, enter the name of the module packt.addressbook and click Finish:

And just like that, you've created a new module...

The address book viewer application

Now that you are comfortable creating, compiling, and executing a simple Java 9 module, let's update it and start adding address book viewer functionality.

The following informal class diagram shows how we'll design the application classes to begin with:

The main class has the main() method that displays the list of contacts in ascending order, sorted by the lastName property. It gets the list of contacts by calling the ContactUtil.getContacts() method and it sorts it using SortUtil.sortList(). It then displays the list of contacts to the console.

We'll start with a new model class Contact, which represents a single piece of contact information. Apart from the obvious contact-related private member variables and getters and setters, this class also has a couple of additions that'll come in handy later:

  • The constructor with...

Handling possible errors

Here are some possible errors you could run into when following the steps we previously outlined, along with some solutions:

  1. Error during compilation:
      javac: invalid flag: --module-source-path 

This is probably because you haven't switched to JDK 9 and are still using the Java 8 compiler. The --module-source-path option has been newly introduced to  javac as of version 9.

  1. Error during compilation:
      error: module not found: packt.addressbook 

This error is because the Java compiler is unable to find the module-info.java file. Make sure it is in the right directory path.

  1. Error during runtime:
      Error occurred during initialization of VM 
      java.lang.module.ResolutionException: Module packt.addressbook
not found

This error indicates that the module file is not available in the module path provided. Make sure the path...

Summary

In this chapter, you have learned what the bare minimum steps to creating a Java 9 module are. You've created a simple module from scratch, as well as compiled and executed code in the module. You've also learned about a few possible error scenarios and how to handle them.

There is something missing though! Since we are dealing with a single module, we are not really leveraging the concepts of modularity here. The concepts of modularity come into play only when we have multiple modules interacting with each other. You'll see just that in action in the next chapter when you create your second Java module and set up inter-module dependency!

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Master design patterns and best practices to build truly modular applications in Java 9
  • Upgrade your old Java code to Java 9 with ease
  • Build and run a smooth functioning multi-module application.

Description

The Java 9 module system is an important addition to the language that affects the way we design, write, and organize code and libraries in Java. It provides a new way to achieve maintainable code by the encapsulation of Java types, as well as a way to write better libraries that have clear interfaces. Effectively using the module system requires an understanding of how modules work and what the best practices of creating modules are. This book will give you step-by-step instructions to create new modules as well as migrate code from earlier versions of Java to the Java 9 module system. You'll be working on a fully modular sample application and add features to it as you learn about Java modules. You'll learn how to create module definitions, setup inter-module dependencies, and use the built-in modules from the modular JDK. You will also learn about module resolution and how to use jlink to generate custom runtime images. We will end our journey by taking a look at the road ahead. You will learn some powerful best practices that will help you as you start building modular applications. You will also learn how to upgrade an existing Java 8 codebase to Java 9, handle issues with libraries, and how to test Java 9 applications.

Who is this book for?

This book is written for Java developers who are interested in learning and understanding the techniques and best practices to build modular applications in Java. The book assumes some previous programming experience in Java 8 or earlier, familiarity with the basic Java types such as classes and interfaces, as well as experience in compiling and executing Java programs.

What you will learn

  • • Get introduced to the concept of modules and modular programming by working on a fully modular Java application
  • • Build and configure your own Java 9 modules
  • • Work with multiple modules and establish inter-module dependencies
  • • Understand and use the principles of encapsulation, readability, and accessibility
  • • Use jlink to generate fully loaded custom runtime images like a pro
  • • Discover the best practices to help you write awesome modules that are a joy to use and maintain
  • • Upgrade your old Java code to use the new Java 9 module system

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 29, 2017
Length: 298 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126275
Vendor :
Oracle
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 29, 2017
Length: 298 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126275
Vendor :
Oracle
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 99.97
Design Patterns and Best Practices in Java
€36.99
Modular Programming in Java 9
€29.99
Java 9 Data Structures and Algorithms
€32.99
Total 99.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Introducing Java 9 Modularity Chevron down icon Chevron up icon
Creating Your First Java Module Chevron down icon Chevron up icon
Handling Inter-Module Dependencies Chevron down icon Chevron up icon
Introducing the Modular JDK Chevron down icon Chevron up icon
Using Platform APIs Chevron down icon Chevron up icon
Module Resolution, Readability, and Accessibility Chevron down icon Chevron up icon
Introducing Services Chevron down icon Chevron up icon
Understanding Linking and Using jlink Chevron down icon Chevron up icon
Module Design Patterns and Strategies Chevron down icon Chevron up icon
Preparing Your Code for Java 9 Chevron down icon Chevron up icon
Migrating Your Code to Java 9 Chevron down icon Chevron up icon
Using Build Tools and Testing Java Modules Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(2 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
Java_Guy Sep 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is one of the best book I came across recently. Author had really explained the topics well so as to understand the core concepts of Modular Programming in Java 9. I will certainly recommend this book to readers !!
Amazon Verified review Amazon
Mozart Brocchini Sep 07, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Disclaimer: I was a technical reviewer of this book.The author gently introduces all concepts and then applies them with simple code examples or executing new commands on the terminal that were specifically added to Java 9 to help with modularity features.You will start by learning what problems the modularity features solve, then learn how to create your first module and progress incrementally all the way up to migrating existing code to java 9 and ultimately using modules with build tools and testing modules. You will also learn how the Java platform itself has been modularized and what benefits that brings. There is a new game changer feature that you shouldn't miss, the linking development phase which happens between compiling and executing code. Linking allows you to create self contained lightweight runtime images for your application with the usage of jlink tool rather then having to deploy the entire rt.jar like we did with previous versions of Java.I started reading this book with a lot of skepticism, my initial thinking was "Does modularity add any value to software development in today's world where modern architectures just expose APIs backed by microservice back ends ?". Well, it turns out that some of the new modularity features added to Java 9 like linking, actually help with creating more lightweight services.Fortunately, it turns out that this book will help Java 9 programmers with all the tasks related to modularity, including module design, best practices and patterns for modularizing new applications as well as retrofitting existing monoliths into modular systems which could later be broken into standalone microservices.I'm giving a four star rating based on topic coverage and accuracy, this book is excellent because it has everything you need to know about modularity with Java 9, you will find articles on web containing certain concepts but likely all articles will be incomplete and you will be only getting part of what Java 9 modules are about. While it is tempting to jump into learning the modularization features based on short tutorials, the modularity features are game changers and may only disappoint you if you start with a high level of frustration when failing to get things things done because of lack of knowledge. Just to give you and idea on how Java 9 is different, in Java 9 modular development, the classpath is no longer used to find dependencies.I obviously have not read all Java 9 books and never will, but my guess is that even Java 9 books that are not specifically targeting modularity will likely be short in modularity content.What could be improved:A few examples are based on older architectures and practices, those examples were chosen to exemplify some problems that modularity solve, but those issues no longer exist in more modern applications using microservices architecture and DevOps automation practices.Also, sometimes the topics feel a bit long for an experienced architect like me who wants to go right to the point.The verdict:If you are willing to learn Java modularity the right way, or have a complete reference focused exclusively on the new modularity features added in Java 9, this book is for you.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.