JAVA-RELEASE/JAVA-9

Java 9: Features & Highlights

This article covers features of Java 9 with code examples

Pravinkumar Singh
5 min readJun 12, 2023

Java 9, the ninth major release of the Java language, brought new features, including the Java Platform Module System, REPL (JShell), new language enhancements, and updates to its APIs. By the end, you should have a better understanding of these features of Java 9.

1. Java Platform Module System (JEP 261)

The JPMS, introduced in Java 9 under Project Jigsaw, is a game-changing feature that enables developers to break down complex applications into smaller, more manageable, and efficient modules.

JPMS simplifies building and maintaining large applications, making code more readable, scalable, maintainable, and providing better encapsulation and separation of concerns.

How to Create a Custom Java Module

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

In this example, the ‘module-info.java’ declares that the ‘com.example.myapp’ module requires ‘java.xml’ module and exports ‘com.example.myapp’ package.

package com.example.myapp;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class MyApp {
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
// ...
}
}

The ‘MyApp.java’ file represents the main class in the ‘com.example.myapp’ module, which utilizes the ‘javax.xml.parsers’ package.

2. JShell (JEP 222)

With Java 9, developers have access to the JShell, a Read-Eval-Print Loop (REPL) that allows users to execute Java code snippets instantly without needing to compile full-blown programs.

JShell is an invaluable tool for developers, making it easier to prototype, test, and experiment with code quickly.

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

jshell> int x = 10;
x ==> 10

jshell> int y = x * 2;
y ==> 20

3. Language Enhancements

Java 9 introduces various language enhancements, improving the programming experience and simplifying code.

3.1. Private Interface Methods (JEP 213)

Java 9 allows interface methods to be declared as ‘private’. It assists in separating common code from other default methods within the interface.

public interface Vehicle {
default void start() {
powerOn();
System.out.println("Vehicle started");
}

default void stop() {
powerOff();
System.out.println("Vehicle stopped");
}

private void powerOn() {
System.out.println("Powering on...");
}

private void powerOff() {
System.out.println("Powering off...");
}
}

3.2. Try-With-Resources Update (JEP 213)

In Java 9, if a resource implements the AutoCloseable interface, it can be used without enclosing it within the try block.

public class MyResource implements AutoCloseable {
@Override
public void close() {
System.out.println("Closing MyResource...");
}
}

MyResource resource = new MyResource();
try (resource) {
// Use the resource here
}

4. API Updates and New Features

Several updates were introduced into Java 9’s APIs to provide developers with more capabilities and optimized performance.

4.1. Stream API Improvements (JEP 266)

New methods were added to the Stream API to simplify usage and increase efficiency. Here’s an example showcasing the Stream.iterate and Stream.takeWhile methods:

Stream.iterate(1, i -> i <= 10, i -> i + 1)
.takeWhile(i -> i % 2 == 0)
.forEach(System.out::println);

4.2 The Optional API Enhancements (JEP 269)

Java 9 introduces new methods in the Optional class for better handling of optional values, such as stream(), or(), and ifPresentOrElse():

Optional<String> optionalValue = Optional.of("Java 9");

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

// Demonstrate or()
Optional<String> optionalNewValue = optionalValue.or(() -> Optional.of("Fallback Value"));
System.out.println(optionalNewValue.get());

// Demonstrate stream()
List<String> values = optionalValue.stream().collect(Collectors.toList());
System.out.println(values);

4.3. The ProcessHandle API (JEP 102)

Java 9 introduces the ProcessHandle API for improved process control and system management, allowing developers to discover, monitor, and manage native processes.

// Get current Process
ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("Current Process ID: " + currentProcess.pid());

// Get Process Information
ProcessHandle.Info info = currentProcess.info();
System.out.println("Process Info: " + info);

// Retrieve the process tree
ProcessHandle.allProcesses().forEach(process -> {
System.out.println("Process ID: " + process.pid());
});

4.4. HttpClient API (JEP 110)

The new HttpClient API in Java 9 offers enhanced support for HTTP/2, asynchronous programming, and improved performance over the older HttpURLConnection class. Note that HttpClient was an Incubator feature in Java 9 and became a standard API in Java 11.

HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();

HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build();

CompletableFuture<HttpResponse<String>> httpResponse = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());

httpResponse.thenApply(HttpResponse::body).thenAccept(System.out::println);

5. Diamond Operator Extension (JEP 213)

Allowing diamond with anonymous classes if the argument type of the inferred type is denotable: This change allows you to use the diamond operator (<>) with anonymous classes in certain situations.

Comparator<String> comparator = new Comparator<>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
};

This feature extends the use of the diamond operator which was previously not allowed with anonymous classes.

6. Convenience Factory Methods for Collections (JEP 269)

This JEP introduces several convenience methods for creating small collections and maps. These methods make it easier to create collections in a more concise and readable way.

List<String> list = List.of("a", "b", "c");
Set<String> set = Set.of("a", "b", "c");
Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 3);

This feature replaces the previous verbose way of creating collections, especially unmodifiable collections.

7. Multi-Resolution Image API (JEP 251)

This JEP introduces an API for handling images with multiple resolutions. This can be useful when creating applications that need to scale images based on the display resolution.

BufferedImage image1 = ImageIO.read(new File("image1.png"));
BufferedImage image2 = ImageIO.read(new File("image2.png"));
MultiResolutionImage image = new BaseMultiResolutionImage(image1, image2);
Image variant = image.getResolutionVariant(16, 16);

8. Deprecate the Applet API for Removal (JEP 289)

This JEP deprecates the Applet API for removal in a future release. Applets were a way of embedding Java applications in a web page, but they are now considered outdated and have been replaced by more modern web technologies. This feature marks the Applet API as deprecated and schedules it for removal, replacing it with more modern web technologies.

9. HTML5 Javadoc (JEP 224)

This JEP updates the standard doclet in Javadoc to generate HTML5 markup. This allows the generated documentation to use more modern web features. This feature replaces the previous HTML 4.01 output from Javadoc.

10. Javadoc Search (JEP 225)

This JEP adds a search box to the Javadoc tool’s generated API documentation. This makes it easier to find classes, methods, and other elements in the documentation.

Conclusion

Although Java 9 offers numerous improvements and features that make development more efficient and streamlined, it's a not big one.

Peace!

Related reads : java-release

--

--