Core Java

Java 9 New Features

Introduction:

Oracle Java 9 has a large set of new features including the various upgrades to the programming tools and libraries. In this tutorial, we’ll have a look at a few of those features.

1.) Java 9 REPL(JShell)

Let’s cover the fun part first!

In Java 9, Oracle introduced a tool called REPL(Read Evaluate Print Loop) or JShell. It helps in testing any Java construct like Class, Interface, statements pretty easily.

The JShell executable can be found in <JAVA_HOME>/bin folder.

jdk-9\bin>jshell.exe
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro
jshell> 10 + 20
$1 ==> 30
jshell> "Programmer Girl".substring(0,10);
$2 ==> "Programmer"

This interactive shell also supports storing and loading the Java statements from a text file.

 

2.) Private Methods In Interface

Java 9 onwards, we can define our private/private static methods within an interface.

public interface Car {
    
    private void register() {
        ...
    }

    private static void displayCar() {
        ...
    }
}

These methods mean exactly the same as they would mean when declared in a class.

 

3.) Use Of Diamond Operator for Anonymous Inner Class

Java 9 allows us to use the diamond operator when defining our anonymous inner class:

ArithmeticOperations<Integer> obj = new ArithmeticOperations<>() { 
// anonymous inner class
};

This is to reduce verbosity and improve readability.

 

4.) Factory Methods for Immutable List/Set/Map

List and Set interfaces now have of() methods to help us create an empty or non-empty Immutable List or Set objects:

List immutableEmptyList = List.of();

List immutableNonEmptyList = List.of("A", "B", "C");

Set immutableEmptySet = Set.of();

Set immutableNonEmptySet = Set.of("A", "B", "C");

On similar lines, we can create an immutable Map:

Map immutableEmptyMap = Map.of();

//[1:"A", 2:"B", 3:"C"]
Map immutableNonEmptyMap = Map.of(1, "A", 2, "B", 3, "C");

Since these are all immutable, any attempt to add/remove elements from them would result in UnsupportedOperationException being thrown.

 

5.) Java 9 Modular Programming

Let’s discuss one of the key features introduced in Java 9. The modular approach to programming will reduce the execution time and memory requirements significantly.

As described in its documentation:

The primary goals of Project Jigsaw are to make implementations of the Platform more easily scalable down to small devices, improve security and maintainability, enable improved application performance, and provide developers with better tools for programming in the large.

All the module definitions must go in a file named module-info.java, which would look similar to:

module com.programmergirl.java9.modules.student {
    requires com.programmergirl.java9.modules.person;
    exports com.programmergirl.java9.modules.student.management;
    exports com.programmergirl.java9.modules.student.history;
}

 

6.) Stream API Enhancements

Java 9 added a few more default methods to java.util.Stream interface:

  • default Stream<T> takeWhile(Predicate<? super T> predicate): It takes all the values until the predicate returns false
  • default Stream<T> dropWhile(Predicate<? super T> predicate): It drops all the values until the predicate returns true for the first time
  • static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next): It allows defining hasNext parameter which stops the loop once hasNext predicate returns false
  • static <T> Stream<T> ofNullable(T t): Introduced to avoid explicit null pointer checks for streams
//prints AB
Stream.of("A","B","","C","D").takeWhile(s->!s.isEmpty())
  .forEach(System.out::print);

//prints CD
Stream.of("A","B","","C","D").dropWhile(s->!s.isEmpty())
  .forEach(System.out::print);

//1234
IntStream.iterate(1, n -> n < 5, n -> n + 1).forEach(System.out::print);

 

7.) Optional To Stream

java.util.Optional.stream() method helps us work with streams over optional elements:

List<Integer> myList = listOfOptionalElements.stream()
  .flatMap(Optional::stream)
  .collect(Collectors.toList());

8.) Try With Resources Improvement

In Java 7 or 8, the try-with-resources syntax requires us declaring a new variable for each resource being managed by the statement.

As of Java 9, if our resource is being referenced by a final or effectively final variable, a try-with-resources statement can manage a resource without the need of declaring a new variable.

AutoCloseableImpl myResource = new AutoCloseableImpl();
try (myResource) {
    // do some stuff with myResource
}

9.)  Http-2 Client

Jave 9 introduced new Https -2 Client API in incubator module. It is an improvement over legacy Http Client API which had performance issues and also lacked support for Http 2 protocol.

This new API supports both synchronous as well as asynchronous modes of operation. It lives under the jdk.incubtor namespace.

HttpRequest httpRequest = HttpRequest.newBuilder()
  .uri(new URI("http://programmergirl.com/"))
  .GET()
  .build();

HttpResponse<String> httpResponse = HttpClient.newHttpClient()
  .send(httpRequest, HttpResponse.BodyHandler.asString());

 

10.)  Miscellaneous Features:

  • Multi-Resolution Image API: One important class in this API is java.awt.image.MultiResolutionImage. It encapsulates a set of images with different widths and heights (i.e. in different resolutions) and allows us to query them based on our requirements.

 

  • Process API Improvements:  To ease out the management and control of processes, a few new classes and methods have been added. Two new important interfaces in Process API:
    • java.lang.ProcessHandle
    • java.lang.ProcessHandle.Info
      ProcessHandle currentProcess = ProcessHandle.current();
      System.out.println("Current Process Id: = " + currentProcess.getPid());
      
      ProcessHandle.Info currentProcInfo = currentProcess.info();
      Optional<Duration> cpuUtilization = currentProcInfo.totalCpuDuration();
      

       

  •  Reactive Streams: Java 9 introduced Reactive Streams API which helps to build asynchronous, scalable and parallel applications pretty easily. It is based on the Publisher/Subscriber model. Some of the important interfaces include:
    • java.util.concurrent.Flow
    • java.util.concurrent.Flow.Publisher
    • java.util.concurrent.Flow.Subscriber
    • java.util.concurrent.Flow.Processor

Conclusion

In this tutorial, we were introduced to the key features of Java 9. Some of those include Jigsaw Project – Modular System, JShell, Improvements in Stream and Optional, Multi-Resolution Image API, Reactive Streams etc.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *