Wednesday, March 7, 2018

Java 9 Features with examples

Java 9 Features with Examples

The Java language has seen a lot of changes over the years since JDK1.0 released in 1996. Over the years, apart from the language changes, there have been many dramatic changes in the Java Class Library which has grown to more than 3000 classes. Where Java 8 saw lambdas, streams and API changes Java 9 is mainly about Jigsaw and jshell. Released on 21 September 2017 with the final release with all critical bug fixes released on 16 January 2018, almost three years after Java 8 there are several key changes in this release. 
See Also : Collection Framework in java

What makes Java 9 different from Java 8?

Java 8 provided developers with a lot of versatility which enabled them to provide to a range of businesses and with Java 9 there is a promise of added versatility and high customizability.
One of the major differences between Java 8 and 9 is the modularization (Project Jigsaw) provided in Java 9. This has enabled the software to become more robust as it is more reusable which in turn makes it easier to debug and manage.

The introduction of Jshell comes as a long-awaited and welcome feature. It includes auto-completion and history features which make it a handy tool for beginners and experts alike.
With the improvements in the Collection Factory Methods creation of a List will be accomplished in a single line of code unlike Java 8.

The HTTP 2.0 client support will provide greater speed.

A small but significant update comes with the addition of search in Javadocs.
The enhanced Multi Release Jar file will now allow multiple Java Release class/resource files to coexist. This will encourage more users to update to the newer versions of Java as earlier coding for conditional platform dependencies was difficult.

The Java updates and security releases have always had a confusing versioning system. Up until Java 8, odd numbers were given to all the critical patches and the limited updates were given even numbers. With Java 9’s New Version-String Scheme, there is some uniformity that has been introduced. The version number will be of arbitrary length but it will contain 3 parts at the start:
  • Major Version Number – JDK 8 will be 8, JDK 9 will be 9 and so on.
  • Minor Version Number – Maintenance releases for the major release.
  • Security – This will be updated whenever a security update will be released

Streams introduced in Java 8, using which aggregate operations from a sequence of objects could be performed by developers. Java 9 has made it even easier by adding a few more utility methods.
  • Takewhile(Predicate Interface) and dropwhile(Predicate Interface)
  • Iterate(initialize section; predicate section(hasNext); next section)
  • ofNullable()

See Also Important Interview Questions

Java 9 Features and Examples

  • Platform Module System – Project Jigsaw

This is one of the major changes in Java 9. Few of the major issues we face in imports are finding out if all the required jars are included or if there are any duplicate entries. The public modifier provides access to everyone due to which achieving strong encapsulation was difficult so the code was never truly encapsulated.
The Module System has a base module called the “java.base” module. This module is not dependent on any other module and by default, all other modules depend on this base module.
A Module is nothing but a collection of Java programs. Every Java 9 Module will have a Module and its descriptor (“”). A module is created by using the module identifier. The module descriptor file will define:
    • Module Name: The name of the module is similar to the naming of packages i.e. it follows the reverse-domain-pattern. The name of the module should be the same as the name of the directory containing its resources.
    • Exports: It lists what the module exports.
    • Requires- This is the list of modules on which it depends. The java.base module will always be included. Even an empty module descriptor will contain the java.base module.
      The looks like this:

The advantages of this feature can be summed up as follows:
    • The java source code will be divided into smaller modules which will, in turn, provide testable and maintainable code.
    • Only the necessary modules are included making the module size significantly smaller which will also help improve performance.
    • The creation of modules helps achieve better encapsulation. Most of the internal JDK API’s will be inaccessible, barring a few critical ones.
    • The users will be able to create their own modules for their applications.
    • Linking – JDK itself being modularized and all the modules having explicit dependencies makes it possible to create a minimal runtime environment with only the basic modules required to run the application. The new jlink tool in Java 9 makes this possible. A runtime image can be created for shipping your application instead of the fully loaded JDK installation that was used earlier.

  • Jshell – REPL

JShell or Java Shell is a Read Evaluate Print Loop (REPL) tool. Many languages like Scala already have this feature and now Java too has it. This new tool introduced in Java 9 is nothing but a command-line interface which enables us to execute and test any Java constructs
Once you open the command prompt, make sure you have Java version 9 by running Java –version to use the jshell. The jshell does not require any IDE or any kind of editor which makes it very convenient for java first timers and also experts to quickly check new features or test small code snippets. The entire overhead of opening an editor, typing the code, saving and compiling it successfully and then running it without runtime errors for testing a small piece of business logic has reduced
    • Any valid java expression can be tested.
    • Variables can be declared and used anywhere throughout the Jshell session.
    • The semicolon(;) is optional.
    • Scratch Variables are created if a variable name is not provided. These variable names start with dollar($) sign.
    • /import command can be used to see the default imported packages.
    • /vars can be used to show the variables created.
    • /list gets the entire source code that has been written.

  • Interface Private Methods

Interfaces can now include behaviour also in addition to default methods and static methods introduced in Java 8. These methods will act like any private methods of a class. This helps avoid redundant code and increases reusability. Earlier, if there was a need for a default implementation, an abstract class had to be created. Now we can add private and private static methods to interfaces which will provide reusability without exposing the method to everyone.
Now we can write the default implementation for all the methods thereby reducing a significant amount of redundant code.

  • Try With Resources

In the previous versions, Java 7 and Java 8, a new local variable had to be created to be used in the try block. In Java 9, this compulsion of creating a local variable has been removed. Now we can use an existing variable in the try block as a resource provided that it is final or effectively final. This has helped in reducing a lot of redundant code.
Until Java 8, we would have had to create a new variable to use in the try block. Now we can use the already created “reader1” variable

  • HTTP 2.0 Client full support

HTTP has evolved over the years since it was introduced in 1997. The use of HTTP evolved over tie but the Java API did not keep up with the change. With Java 9, a cleaner and clearer API has been introduced.
There are 3 classes through which the HTTP connections are handled in the new API.
    • HTTPClient – For creating and sending requests.
    • HTTPRequest – To construct the request that is sent via HTTPClient.
    • HTTPResponse – To hold the response that is sent.
The HTTP connections can be maintained more easily with the new API. More responsive application is possible without any calls to third-party libraries which also makes it faster.
We can also execute asynchronously by calling responseAsync() as follows:

  • Process API Updates

Java 9 introduces a cleaner approach to spawning new processes and getting process information. The java.lang.Process class has been enhanced and a new java.lang.ProcessHandle interface and a nested Info interface have been introduced.
The ProcessHandle.Info API can be used to obtain a lot of information including:

    • User who created the process and the total time spent by it.
    • When the process started·
    • The command that started the process.
    •  The arguments of the command


The list of all the processes that are running in the system can be acquired by using the allProcesses() static method
The direct children of the current process are given by the children() api and the descendents() api can be used to get the descendants.
On the onExit() method of ProcessHandle a java.util.concurrent.CompletableFuture object is returned. We can invoke an action on the termination of the process using this object. It doesn’t matter if the process was successful or not.

  • Improved Anonymous Classes

Now it is possible to infer classes in the Anonymous inner class when the diamond operator is used.
In Java 8 the following code would result in an error.
Now, In Java 9 the diamond operator is allowed in Anonymous Inner Classes

  • @SafeVarargs annotation

This annotation was used to suppress warning. This could be applied to constructors, static and final methods. Now it can also be applied to private methods

In earlier versions of Java, there was a way to create Immutable Collection objects using the Collections class utility method.
For example, if I want to create a list I used the Collections.unmodifiableList() method. Now, if there a finite set of known values to be added, I had to make multiple calls to the add() method to populate the list.
With Java9, many utility methods have been introduced to the List, Set and Map interfaces. Highly optimized collection implementations for the elements added are returned from these methods as they are immutable.
of” methods have been introduced to create empty or non-empty immutable Collections objects
    • List and Set have the following implementation for the “of “method to create empty and non-empty objects
    • The Map interface has 2 sets of methods, one to create immutable Map object and one to create immutable Map.Entry object
Above all are the basic features and Implementation Snippet of the Java 9 Changes 

If you like this article please share it with your friends and colleagues.

Happy Learning
Thanks for reading


Post a Comment