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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781787126909
Vendor :
Oracle
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
€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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.