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
$9.99 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 : 9781787126909
Vendor :
Oracle
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 131.97
Design Patterns and Best Practices in Java
$48.99
Modular Programming in Java 9
$38.99
Java 9 Data Structures and Algorithms
$43.99
Total $ 131.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela