Java 9 Features

1. ✅ Java Platform Module System (Project Jigsaw)

Problem it solves: Makes Java more scalable and secure by breaking JDK into modules.

Example:

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

This allows you to control which packages are visible and reduces runtime size.


2. ✅ JShell (REPL - Read Evaluate Print Loop)

Description: An interactive shell for trying out Java code quickly without writing boilerplate.

Example (in terminal):

jshell> int a = 5
a ==> 5

jshell> System.out.println(a * 10)
50

Great for learning, testing, or demoing code snippets.


3. ✅ Private Methods in Interfaces

Problem it solves: Allows code reuse inside default and static methods in interfaces.

Example:

interface MyInterface {
    default void show() {
        log("Showing");
    }

    private void log(String message) {
        System.out.println("Log: " + message);
    }
}

4. ✅ Try-With-Resources Enhancement

Improvement: Now you can use already-declared resources outside the try block.

Example:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try (br) {
    System.out.println(br.readLine());
}

No need to re-declare the resource inside the try block.


5. ✅ Factory Methods for Collections (List, Set, Map)

Problem it solves: Allows concise creation of immutable collections.

Example:

List<String> list = List.of("A", "B", "C");
Set<Integer> set = Set.of(1, 2, 3);
Map<String, Integer> map = Map.of("a", 1, "b", 2);
  • These collections are immutable.
  • Duplicate keys or nulls will throw exceptions.

6. ✅ Stream API Improvements

  • takeWhile(), dropWhile(), and iterate() enhancements.

Example:

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);

numbers.stream()
       .takeWhile(n -> n < 4)
       .forEach(System.out::println); // 1 2 3

7. ✅ Optional Enhancements

  • ifPresentOrElse(), or()

Example:

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

name.ifPresentOrElse(
    System.out::println,
    () -> System.out.println("Not found")
);

8. ✅ HttpClient (Incubator Module)

  • Replaces the old HttpURLConnection
  • Modern API with async support

Example:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://example.com"))
    .build();

client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println);

Note: Became standard in Java 11.


9. ✅ Process API Enhancements

Example:

ProcessHandle current = ProcessHandle.current();
System.out.println("PID: " + current.pid());

Can now get information about the current or child processes more easily.


10. ✅ Deprecated APIs and Removed Features

Java 9 also cleaned up legacy APIs and deprecated some older methods/classes.



Back to blog

Leave a comment

Please note, comments need to be approved before they are published.