0% found this document useful (0 votes)
7 views11 pages

Java 9 Features Overview and Examples

Java 9 introduces several key features including the Java Platform Module System for modular programming, a new JShell REPL for testing code snippets, and enhancements to the Streams API with new methods like takeWhile and dropWhile. It also allows private methods in interfaces, provides factory methods for creating immutable collections, and improves the try-with-resources statement. Additional features include multi-release JAR files, a new HTTP/2 client, and enhancements to Javadoc and string storage.

Uploaded by

vaibhavkinge026
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

Java 9 Features Overview and Examples

Java 9 introduces several key features including the Java Platform Module System for modular programming, a new JShell REPL for testing code snippets, and enhancements to the Streams API with new methods like takeWhile and dropWhile. It also allows private methods in interfaces, provides factory methods for creating immutable collections, and improves the try-with-resources statement. Additional features include multi-release JAR files, a new HTTP/2 client, and enhancements to Javadoc and string storage.

Uploaded by

vaibhavkinge026
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java - Java 9 Features Summary

hey list me all java 9 features

Sure! Here's a comprehensive list of Java 9 features, grouped into categories with short explanations
for each:

✅ 1. Modularity
🔹 Project Jigsaw (Java Platform Module System - JPMS)
Introduced modular programming to the JDK.

Code can be split into modules using `[Link]`.


Helps with:

Better encapsulation

Reduced JAR size

Faster startup

Easier deployment

📌 Example:
java

module [Link] {
requires [Link];
exports [Link];
}

✅ 2. JShell (REPL)
JShell is a Read-Eval-Print Loop for Java.

You can test Java code snippets without creating a full class.

📌 Example:
jshell

jshell> int a = 10
a ==> 10

jshell> [Link](a * 2)
20

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/11
✅ 3. Improvements to Streams API
New methods added:
`takeWhile()`

`dropWhile()`

`ofNullable()`

`iterate()` (enhanced version)

📌 Example:
java

List<Integer> list = [Link](1, 2, 3, 4, 5, 6);


[Link]().takeWhile(n -> n < 4).forEach([Link]::println);

✅ 4. Interface Private Methods


Interfaces can now have private and private static methods.

📌 Example:
java

interface MyInterface {
private void log(String msg) {
[Link]("Log: " + msg);
}

default void doSomething() {


log("Doing something");
}
}

✅ 5. Factory Methods for Collections


New static methods: `[Link]()`, `[Link]()`, `[Link]()` to create immutable collections.

📌 Example:
java

List<String> list = [Link]("A", "B", "C");


Set<Integer> set = [Link](1, 2, 3);
Map<String, Integer> map = [Link]("a", 1, "b", 2);

✅ 6. Enhanced try-with-resources
Resources can be effectively final variables declared outside the try block.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/11
📌 Example:
java

BufferedReader reader = new BufferedReader(new FileReader("[Link]"));


try (reader) {
[Link]([Link]());
}

✅ 7. Deprecated and Removed APIs


Many internal APIs are deprecated (e.g., `[Link]`).

Encourages use of official supported APIs.

✅ 8. Multi-Release JAR Files


You can create JARs with different versions of class files for different Java versions.

📌 Use:
bash

META-INF/versions/9/...

✅ 9. Process API Enhancements


`ProcessHandle` and `[Link]` to get PID, CPU time, user, etc.

📌 Example:
java

ProcessHandle current = [Link]();


[Link]("PID: " + [Link]());

✅ 10. HTTP 2 Client (Incubator Module)


Introduced a new HTTP/2 client API as an incubator (`[Link]`).

Replaced the old `HttpURLConnection`.

✅ 11. Stack-Walking API


Efficient stack trace processing via `StackWalker`.

📌 Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/11
java

StackWalker walker = [Link]();


[Link]([Link]::println);

✅ 12. Improvements in Javadoc


Javadoc now has a search box and generates HTML5 output.
Can include runtime API usage examples.

✅ 13. Compact Strings


Java 9 stores strings internally as byte[] with encoding metadata, improving memory usage for
Latin-1 characters.

✅ 14. Miscellaneous Updates


Unified JVM Logging (JEP 158)
Ahead-of-Time (AOT) Compilation (JEP 295) for limited use

G1 becomes default garbage collector


Platform logging API and service

Let me know if you'd like deep explanations or examples for any specific feature.

can you explain more deep in 3 4 5 6

Absolutely! Let’s dive deeply into Java 9 features #3, #4, #5, and #6 with explanations, examples, and
internal behavior:

✅ 3. Stream API Enhancements


Java 9 enhanced the `Stream` API with 4 powerful methods to handle conditional data flows:

🔹 `takeWhile(Predicate<T>)`

Keeps taking elements from the stream until the predicate returns false.
Once false is encountered, remaining elements are skipped.

📌 Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/11
java

List<Integer> numbers = [Link](1, 2, 3, 4, 1, 2, 3);


[Link]()
.takeWhile(n -> n < 4)
.forEach([Link]::println); // Output: 1 2 3

🔍 Why? The moment `4` appears (not `< 4`), it stops processing.

🔹 `dropWhile(Predicate<T>)`

Skips elements as long as the predicate is true.

Starts collecting once predicate becomes false.

📌 Example:
java

[Link]()
.dropWhile(n -> n < 4)
.forEach([Link]::println); // Output: 4 1 2 3

🔍 Why? Drops 1, 2, 3; starts from 4 onward.


🔹 `ofNullable(T value)`

Converts a nullable object to a stream.

If value is null → returns an empty stream.

📌 Example:
java

Stream<String> stream = [Link](null);


[Link]([Link]()); // Output: 0

🔹 Enhanced `iterate()`

Old version only supported infinite loops.


Java 9 added a predicate-based version.

📌 Example:
java

[Link](1, n -> n <= 10, n -> n + 1)


.forEach([Link]::println); // 1 to 10

✅ 4. Interface Private Methods


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/11
🚀 Why?
To reuse common logic among `default` and `static` methods inside the interface only.

🔹 Before Java 9:
java

interface MyInterface {
default void methodA() {
[Link]("Do A");
}
default void methodB() {
[Link]("Do B");
}
}

🔍 Code duplication if A and B share internal logic.


🔹 Java 9 – Private Methods:
java

interface MyInterface {
private void log(String msg) {
[Link]("Logging: " + msg);
}

default void methodA() {


log("A called");
}

default void methodB() {


log("B called");
}
}

📌 You can now create:


`private` → Used by default methods
`private static` → Used by static methods

⛔ These methods are not visible to implementing classes.


✅ 5. Factory Methods for Collections
Helps create immutable lists, sets, and maps quickly and safely.

🔹 Why?
Before Java 9:

java

List<String> list = new ArrayList<>();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/11
[Link]("A");

Now, simpler:

java

List<String> list = [Link]("A", "B", "C");


Set<Integer> set = [Link](1, 2, 3);
Map<String, Integer> map = [Link]("a", 1, "b", 2);

🔒 Immutable Nature
These collections are immutable:

java

[Link]("D"); // ❌ Throws UnsupportedOperationException

🔥 Rules and Exceptions


No duplicates allowed in `[Link]()` or `[Link]()`
Nulls are not allowed

java

[Link](1, 2, 2);
[Link](null);
//
//

❌ IllegalArgumentException
NullPointerException

✅ 6. try-with-resources Enhancement
🔹 Before Java 9:
You had to declare the resource inside the try:

java

try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {


[Link]([Link]());
}

🔹 Java 9 – External Resource


Now, you can use effectively final variables (not reassigned) declared outside the try block.
📌 Example:
java

BufferedReader br = new BufferedReader(new FileReader("[Link]"));


try (br) {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/11
[Link]([Link]());
}

🔍 Why useful?
Improves readability

Useful when the resource needs to be accessed before and after the try block

⛔ Still must implement `AutoCloseable`

💡 Summary Table:
Feature Purpose Key Advantage
Stream API Enhanced conditional operations Efficient data filtering

Private Methods Inside interfaces Code reuse + cleaner default methods


Factory Methods Quick immutable collections Less code, safer, thread-safe

try-with-resources External resource support Cleaner resource handling

Would you like exercises or visuals for any of these?

Enhanced iterate()
Old version only supported infinite loops.

Java 9 added a predicate-based version.

📌 Example:
java
Copy
Edit
[Link](1, n -> n <= 10, n -> n + 1)
.forEach([Link]::println); // 1 to 10

can you explain more depply

Absolutely, let’s deeply understand the enhanced `[Link]()` method introduced in Java 9,
how it works internally, and how it differs from the old version.

🔍 What is `[Link]()`?

🔹 Old version (Java 8):


java

[Link](seed, unaryOperator)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/11
Creates an infinite stream starting from `seed`.

Applies `unaryOperator` to generate the next element.


Needs to be manually limited.

📌 Example:
java

[Link](1, n -> n + 1)
.limit(10)
.forEach([Link]::println); // 1 to 10

🆕 Java 9 Enhancement:
java

[Link](seed, hasNextPredicate, unaryOperator)

🔍 Method Signature:
java

static <T> Stream<T> iterate(T seed,


Predicate<? super T> hasNext,
UnaryOperator<T> next)

✅ Parameters:
`seed` – the initial value.
`hasNext` – a predicate (boolean condition) that controls when to stop.

`next` – how to compute the next value.

📌 Example:
java

[Link](1, n -> n <= 10, n -> n + 1)


.forEach([Link]::println);

✅ Execution Flow:
Iteration Value Predicate Check (`n <= 10`) Printed?
1 1 ✅ true ✅ yes
2 2 ✅ true ✅ yes
... ... ... ...
10 10 ✅ true ✅ yes
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/11
Iteration Value Predicate Check (`n <= 10`) Printed?

11 11 ❌ false ❌ no
🔍 As soon as the predicate fails, the stream terminates.
✅ Deep Internals – How It Works:
1. Starts with `seed` = `1`
2. Checks `hasNext` ⇒ `1 <= 10` → true → print

3. Applies `unaryOperator`: `n + 1` → 2

4. Repeats steps until `hasNext` returns false

This eliminates the need for `limit()` in many use cases.

✅ Real-World Use Case:


🔹 Even numbers between 10 and 30:
java

[Link](10, n -> n <= 30, n -> n + 2)


.forEach([Link]::println); // 10, 12, ..., 30

🔹 Loop until a condition from outside is met:


java

int limit = 50;


[Link](1, n -> n * n < limit, n -> n + 1)
.forEach([Link]::println); // 1 to 7

(`8*8 = 64` which is > 50, so loop ends before that)

❗ Key Differences: Java 8 vs Java 9


Aspect Java 8 Java 9
Type Infinite stream Finite or infinite

Limiting Manual using `.limit()` Automatic using `Predicate`

Signature `iterate(seed, op)` `iterate(seed, predicate, op)`


Control Flow No built-in exit condition Built-in condition check with predicate

Performance & Safety May hang if `.limit()` is missed Safer – exits when predicate fails

🧠 Why It’s Important:


Makes declarative iteration safer and easier.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/11
Avoids mistakes like forgetting `.limit()` which can cause infinite loops.

Enhances readability and maintainability.

Would you like to see how to use this enhanced `iterate()` with filtering, mapping, or collecting in real-
world scenarios (like pagination, Fibonacci, etc.)?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/11

Common questions

Powered by AI

Factory methods for collections such as `List.of()`, `Set.of()`, and `Map.of()` in Java 9 provide a simpler and safer way to create immutable collections. These methods reduce code complexity and ensure collections are immutable by default, which is beneficial for thread safety and preventing accidental modifications. Additionally, they enforce constraints like disallowing duplicate elements in sets and maps, and null elements, which enhance the robustness of the code .

The enhanced try-with-resources statement in Java 9 allows the use of effectively final variables outside the try block, improving readability and resource management. This enables developers to declare resources like a `BufferedReader` outside the `try` block, thus allowing these resources to be accessed both before and after the block, provided they implement `AutoCloseable`. It promotes cleaner and more organized code while managing resources efficiently .

Java 9’s stack-walking API provides a more efficient and flexible way to access stack trace information, which is crucial for debugging and monitoring. The `StackWalker` class allows on-demand access to stack frames, reducing the overhead compared to old methods like `Throwable.getStackTrace()`. This enhancement improves performance by allowing selective and lazy access to stack information, which is particularly advantageous in performance-sensitive applications where full stack trace collection could be costly .

Java 9 introduced several enhancements to the Javadoc tool, such as a built-in search box and the generation of HTML5 output, which modernize and improve the usability of generated documentation. These features allow developers to navigate the documentation more efficiently and provide a more engaging user experience. Additionally, Javadoc can now include runtime API usage examples, which aids developers in understanding and using APIs by providing example usages directly within the documentation .

Private methods in interfaces, introduced in Java 9, allow sharing common logic among `default` and `static` methods within an interface without exposing these methods to implementing classes. This reduces code duplication and enhances code modularity by encapsulating helper methods that are only needed internally by the interface, resulting in cleaner and more maintainable code .

The new HTTP/2 client introduced in Java 9 as an incubator (`jdk.incubator.http`) replaces the older `HttpURLConnection` API. This client supports HTTP/2 and WebSocket, providing a more modern, non-blocking, and higher-performance API for handling HTTP communications. It offers improvements in terms of latency and ease of use, aligning with current web standards and providing better performance for modern web applications .

Project Jigsaw, or the Java Platform Module System (JPMS), introduced modular programming to Java 9. This feature allows code to be split into modules using `module-info.java`, which helps with better encapsulation, reduces JAR size, speeds up startup, and simplifies deployment .

Multi-release JAR files in Java 9 allow developers to include version-specific class files for different Java versions within a single JAR file. This feature enhances backward compatibility by enabling a JAR to contain both old and new class versions, ensuring that it can run on different Java runtime environments. Thus, developers can take advantage of new features or optimizations available in newer Java versions without sacrificing compatibility with older versions .

Compact strings in Java 9 improve memory usage by storing strings internally as a `byte[]` instead of `char[]`, along with encoding metadata. For strings consisting only of Latin-1 characters, this reduces memory consumption by nearly 50%, significantly optimizing memory usage for applications with large string datasets. This adjustment benefits overall application performance by reducing the memory footprint, particularly in environments with memory constraints .

Java 9 introduced several enhancements to the Stream API, including new methods like `takeWhile()`, `dropWhile()`, `ofNullable()`, and an enhanced version of `iterate()`. These methods provide powerful tools for conditional data flows, such as processing streams only while a condition is met or dropping elements while a condition is true. The new `iterate()` method allows creating streams with a built-in end condition, reducing the risk of infinite loops and improving both safety and performance .

You might also like