Java 9
About
Java 9 introduced several significant features, primarily focusing on modularity, performance improvements, and API enhancements.
1. Java Platform Module System (JPMS) (Project Jigsaw)
Java 9 introduced the Module System, which allows developers to create modular applications by grouping related classes and packages.
Example:
Step 1: Create a module descriptor file (module-info.java
)
Step 2: Define a package inside the module
Step 3: Use the module in another module
This helps avoid classpath issues and enables strong encapsulation.
2. JShell (REPL)
JShell is an interactive command-line tool that allows developers to execute Java code without writing an entire class or method.
Example (Inside JShell Terminal)
JShell improves learning and testing capabilities without requiring a full Java program.
3. Private Methods in Interfaces
Java 9 allows private methods inside interfaces, reducing code duplication in default and static methods.
Example:
4. HTTP/2 Client (Improved HTTP API)
Java 9 introduced a new HTTP Client API to handle HTTP requests efficiently.
Example:
5. Improved Stream API
Java 9 added new methods in the Stream API to improve functional programming.
New Methods:
takeWhile()
- Takes elements while a condition holds true.dropWhile()
- Drops elements while a condition holds true.ofNullable()
- Creates a stream of a single element or an empty stream.
Example:
6. Factory Methods for Collections
Java 9 introduced immutable factory methods for creating collections. The methods List.of()
, Set.of()
, and Map.of()
in Java 9 return immutable collections, meaning their contents cannot be modified after creation.
Example:
These methods return immutable collections, meaning elements cannot be modified.
7. Try-With-Resources Enhancement
Java 9 improved try-with-resources by allowing resources to be declared outside the try
block.
Example:
8. Process API Enhancements
Java 9 introduced new methods in the Process
API to manage and monitor system processes.
Example:
9. Multi-Release JAR Files
Java 9 allows a JAR to include different versions of classes for different Java versions.
Example Directory Structure:
At runtime, Java 9 will automatically pick the correct version.
10. Improved Optional
API
Optional
APIJava 9 enhanced Optional
with new methods like ifPresentOrElse()
.
Example:
11. Unified JVM Logging
Java 9 introduced a new logging framework for the JVM with a unified format.
Example Command:
This improves JVM performance monitoring and debugging.
12. Compact Strings
Java 9 introduced Compact Strings to optimize memory by using byte arrays instead of char arrays for String storage, reducing memory usage for Latin-1 encoded characters.
Last updated
Was this helpful?