Java 9 Features

Java 9 introduced a range of new features and enhancements to the Java programming language and its runtime. These changes aim to improve performance, enhance developer productivity, and introduce new capabilities for modern application development. In this guide, we'll cover the key features of Java 9, providing examples and links to detailed tutorials.

Check out all Java 9 features tutorials: Java 9 Tutorial.

Key Features of Java 9

  1. Private Methods in Interfaces
  2. Immutable Collections
  3. Stream API Improvements
  4. Optional Class Improvements
  5. JShell - The Interactive Java Shell
  6. Module System (Project Jigsaw)
  7. HTTP/2 Client
  8. Process API Improvements
  9. Miscellaneous Changes
  10. Summary

Let's explore each feature in detail.

1. Private Methods in Interfaces

What are Private Methods in Interfaces?

Java 9 allows interfaces to have private methods, which can be used to share code between default methods. This feature promotes code reusability within interfaces.

Example

interface MyInterface {
    default void defaultMethod() {
        System.out.println("Default Method");
        privateMethod();
    }

    private void privateMethod() {
        System.out.println("Private Method");
    }
}

public class PrivateMethodsExample {
    public static void main(String[] args) {
        MyInterface myInterface = new MyInterface() {};
        myInterface.defaultMethod();
    }
}

Output:

Default Method
Private Method

Explanation

  • private void privateMethod() defines a private method within an interface, which is called by the default method.

Learn more at the link: Java 9 Private Methods in Interface with Examples.

2. Immutable Collections

What are Immutable Collections?

Java 9 introduces static factory methods for creating immutable collections. These methods provide a convenient way to create collections that cannot be modified.

Example

import java.util.List;
import java.util.Set;
import java.util.Map;

public class ImmutableCollectionsExample {
    public static void main(String[] args) {
        // Immutable List
        List<String> immutableList = List.of("A", "B", "C");
        System.out.println("Immutable List: " + immutableList);

        // Immutable Set
        Set<String> immutableSet = Set.of("X", "Y", "Z");
        System.out.println("Immutable Set: " + immutableSet);

        // Immutable Map
        Map<String, Integer> immutableMap = Map.of("One", 1, "Two", 2);
        System.out.println("Immutable Map: " + immutableMap);
    }
}

Output:

Immutable List: [A, B, C]
Immutable Set: [X, Y, Z]
Immutable Map: {One=1, Two=2}

Explanation

  • List.of(), Set.of(), and Map.of() create immutable collections.

Learn more at the links:

3. Stream API Improvements

What are Stream API Improvements?

Java 9 enhances the Stream API with new methods like takeWhile(), dropWhile(), and iterate(). These methods make it easier to work with streams in a functional style.

Example

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamImprovementsExample {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);

        // takeWhile example
        List<Integer> taken = numbers.stream()
                                     .takeWhile(n -> n < 5)
                                     .collect(Collectors.toList());
        System.out.println("takeWhile: " + taken);

        // dropWhile example
        List<Integer> dropped = numbers.stream()
                                       .dropWhile(n -> n < 5)
                                       .collect(Collectors.toList());
        System.out.println("dropWhile: " + dropped);

        // iterate example
        Stream<Integer> iterated = Stream.iterate(0, n -> n < 10, n -> n + 2);
        iterated.forEach(System.out::println);
    }
}

Output:

takeWhile: [1, 2, 3, 4]
dropWhile: [5, 6, 7, 8, 9]
0
2
4
6
8

Explanation

  • takeWhile() and dropWhile() allow conditional processing of elements in a stream.
  • Stream.iterate() is enhanced to include a predicate, providing more control over iteration.

Learn more at the link: Java 9 - Stream API Improvements with Examples

4. Optional Class Improvements

What are Optional Class Improvements?

Java 9 introduces new methods to the Optional class, such as ifPresentOrElse(), or(), and stream(). These methods enhance the functionality of the Optional class, providing more control and flexibility.

Example

import java.util.Optional;

public class OptionalImprovementsExample {
    public static void main(String[] args) {
        Optional<String> optionalValue = Optional.of("Java 9");

        // ifPresentOrElse example
        optionalValue.ifPresentOrElse(
            value -> System.out.println("Value: " + value),
            () -> System.out.println("Value not present")
        );

        // or example
        Optional<String> alternative = optionalValue.or(() -> Optional.of("Alternative"));
        System.out.println("Alternative: " + alternative.get());

        // stream example
        optionalValue.stream().forEach(System.out::println);
    }
}

Output:

Value: Java 9
Alternative: Java 9
Java 9

Explanation

  • ifPresentOrElse() executes an action if the value is present or an alternative action if not.
  • or() provides an alternative Optional if the current one is empty.
  • stream() allows the Optional to be used as a stream.

Learn more at the link: Java 9 - Optional Class Improvements with Examples.

5. JShell - The Interactive Java Shell

What is JShell?

JShell is an interactive tool introduced in Java 9 that allows developers to run Java code snippets quickly without creating a complete program. It is useful for testing code, experimenting with new features, and learning Java.

Example: Using JShell

To use JShell, open your terminal or command prompt and type jshell. You can then enter and execute Java code interactively.

$ jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell> int x = 5;
x ==> 5

jshell> System.out.println(x * 2);
10

jshell> String name = "Java 9";
name ==> "Java 9"

jshell> System.out.println("Hello, " + name);
Hello, Java 9

Explanation

  • JShell provides an interactive environment to run Java code snippets, making it easy to test and experiment with Java features.

Learn more at the links:

6. Module System (Project Jigsaw)

What is the Module System?

Java 9 introduces the module system, also known as Project Jigsaw, which provides a way to modularize applications and the JDK itself. The module system enhances encapsulation and improves the maintainability of large codebases.

Example: Defining a Module

Create a module by defining a module-info.java file:

module com.example.myapp {
    requires java.base;
    exports com.example.myapp;
}

Explanation

  • module com.example.myapp declares a module named com.example.myapp.
  • requires java.base specifies that the module depends on the java.base module.
  • exports com.example.myapp makes the package com.example.myapp accessible to other modules.

7. HTTP/2 Client

What is the HTTP/2 Client?

Java 9 introduces a new HTTP/2 client API that supports HTTP/2, WebSocket, and asynchronous requests. This client provides a more modern and efficient way to handle HTTP communications.

Example: Using the HTTP/2 Client

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Http2ClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                                         .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                                         .GET()
                                         .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Response: " + response.body());
    }
}

Output:

Response: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit..."
}

Explanation

  • HttpClient.newHttpClient() creates a new HTTP/2 client.
  • HttpRequest.newBuilder() constructs an HTTP request.
  • client.send() sends the request and receives the response.

8. Process API Improvements

What are Process API Improvements?

Java 9 enhances the Process API to provide more control over native processes. The improvements include methods for managing process trees, getting process information, and handling process output.

Example: Process API Improvements

public class ProcessApiExample {
    public static void main(String[] args) throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder("notepad.exe");
        Process process = processBuilder.start();

        // Get process information
        ProcessHandle processHandle = process.toHandle();
        System.out.println("Process ID: " + processHandle.pid());
        System.out.println("Is Alive: " + processHandle.isAlive());
        
        // Wait for the process to terminate
        processHandle.onExit().thenRun(() -> System.out.println("Process terminated"));
    }
}

Output:

Process ID: 12345
Is Alive: true
Process terminated

Explanation

  • ProcessBuilder starts a new native process (notepad.exe in this example).
  • ProcessHandle provides information about the process, such as its ID and status.

9. Miscellaneous Changes

Java 9 introduces several other changes, including:

  • Multi-Release JARs: Support for JAR files that can contain classes for different Java versions.
  • Unified JVM Logging: A new logging framework for the JVM, providing a consistent way to log messages.
  • Enhanced @Deprecated: The @Deprecated annotation now supports since and forRemoval attributes.
  • Compact Strings: Optimizes memory usage for String objects by using byte arrays instead of character arrays.

10. Summary

Java 9 brings a wealth of new features and improvements, from the module system to enhancements in the Stream API, Optional class, and more. The introduction of JShell and HTTP/2 client, along with various performance optimizations, make Java 9 a powerful release for modern application development. By understanding and leveraging these features, developers can build more efficient, maintainable, and scalable applications.

Series: Java Release-wise New Features

Comments