Posted on: January 18, 2025 Posted by: rahulgite Comments: 0

Java 11, released in September 2018, is a Long-Term Support (LTS) release, building on Java 10’s features while introducing several improvements and new functionalities. This guide details all the features, their importance, examples, and use cases.


1. Local-Variable Syntax for Lambda Parameters

What Is It?

Java 11 allows the use of var in lambda parameter lists, aligning it with local variable declarations.

Why Was It Introduced?

  • Consistency with var usage in local variables.
  • Simplifies adding annotations to lambda parameters.

Example

Without var:

(x, y) -> x + y

With var:

(var x, var y) -> x + y

With annotations:

(@NotNull var x, @Nullable var y) -> x + (y == null ? 0 : y)

Benefits

  • Simplifies syntax.
  • Enables annotations on lambda parameters.

Limitations

  • Cannot mix var with explicitly typed or untyped parameters.

πŸ”™ Before Java 11 (Java 10 and earlier)

You could not use var in lambda parameters. Lambda parameters had to either:

  • Use explicit types, or
  • Use implicit (inferred) types, but not var.

❌ Invalid in Java 10:

javaCopyEditlist.forEach((var item) -> System.out.println(item)); // ❌ Compile error

βœ… Valid options before Java 11:

javaCopyEditlist.forEach((String item) -> System.out.println(item)); // Explicit type
list.forEach(item -> System.out.println(item));          // Inferred type

βœ… Java 11 and After

Java 11 introduced support for using var in lambda parameter lists, making it consistent with local variable declarations.

βœ… Valid in Java 11+:

list.forEach((var item) -> System.out.println(item));

🧠 Why is this useful?

  • Allows attaching annotations to lambda parameters: list.forEach((@NonNull var item) -> System.out.println(item));
  • Enables more uniform syntax across your codebase.

πŸ“Œ Summary Table:

FeatureJava 10 and EarlierJava 11+
var in lambda parameters❌ Not allowedβœ… Allowed
Annotations on lambda parametersβœ… Only with explicit typesβœ… Works with var too
Type inference in lambda parametersβœ… Yes (without var)βœ… Yes (with or without var)

2. HttpClient API

What Is It?

The HttpClient API, initially introduced in Java 9, was standardized in Java 11. It supports HTTP/2, synchronous and asynchronous requests, and WebSockets.

Why Was It Introduced?

  • To replace HttpURLConnection.
  • Provide modern features like HTTP/2 and non-blocking I/O.

Examples

Synchronous HTTP Request:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

Asynchronous HTTP Request:

client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenAccept(response -> System.out.println(response.body()));

Benefits

  • Simplifies HTTP communication.
  • Supports asynchronous operations with CompletableFuture.

Limitations

  • Requires migration from older APIs.

3. String API Enhancements

What Are They?

New methods in String simplify operations like trimming, checking for blank strings, repeating strings, and handling multiline strings.

New Methods

  • isBlank(): Checks if a string is empty or only contains whitespace.
  • lines(): Splits a string into lines.
  • strip(): Removes leading and trailing whitespace.
  • repeat(): Repeats a string.

Examples

"   ".isBlank(); // true

"Line1\nLine2".lines().forEach(System.out::println);

" Hello ".strip(); // "Hello"

"Java".repeat(3); // "JavaJavaJava"

Benefits

  • Reduces boilerplate.
  • Enhances readability.

Limitations

  • Limited utility outside of text-heavy applications.

4. File API Enhancements

What Are They?

New methods in the Files classβ€”readString() and writeString()β€”streamline reading and writing text files.

Examples

Read String:

Path path = Paths.get("example.txt");
String content = Files.readString(path);

Write String:

Files.writeString(path, "Java 11 Features");

Benefits

  • Simplifies text file handling.
  • Eliminates redundant code.

Limitations

  • Limited to text files; binary files still require streams.

5. Optional Enhancements

What Are They?

New methods in Optional include:

  • isEmpty(): Checks if Optional is empty.
  • stream(): Converts Optional to a stream.

Examples

Optional<String> opt = Optional.empty();
opt.isEmpty(); // true

Optional.of("Java").stream().forEach(System.out::println);

Benefits

  • Better integration with Streams.
  • Enhances null-safe programming.

Limitations

  • Specific to nullable value handling.

πŸ“˜ Before Java 11:

You had to manually check if the Optional had a value before converting it to a stream.

Example:

Optional<String> optional = Optional.of("hello");

Stream<String> stream = optional.isPresent()
? Stream.of(optional.get())
: Stream.empty();

βœ… With Java 11:

Much cleaner with Optional.stream():

Optional<String> optional = Optional.of("hello");

Stream<String> stream = optional.stream();

Now you can directly use Optional inside a stream pipeline, like:

List<Optional<String>> optionals = List.of(Optional.of("a"), Optional.empty(), Optional.of("b"));

List<String> result = optionals.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList()); // ["a", "b"]

πŸ“Œ Summary Table:

VersionWay to convert Optional<T> to Stream<T>
Before Java 11isPresent() + Stream.of() or manual logic
Java 11+optional.stream() simplifies the process

6. Deprecation of Nashorn JavaScript Engine

What Is It?

The Nashorn JavaScript engine was deprecated in Java 11 and removed in later versions.

Why Was It Deprecated?

  • Modern alternatives like GraalVM offer better JavaScript integration.

Impact

Applications relying on Nashorn need migration.


7. Z Garbage Collector (ZGC)

An experimental garbage collector designed for low-latency applications and massive heap sizes.

What Is It?

Key Features

  • Sub-millisecond pause times.
  • Supports heaps from a few MB to terabytes.

Usage

Enable ZGC:

java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC MyApp

Benefits

  • Ideal for real-time systems.
  • Efficient memory management for large heaps.

8. Flight Recorder and Mission Control

What Is It?

Open-sourced diagnostic tools for monitoring and profiling applications with minimal overhead.

Benefits

  • Lightweight monitoring.
  • Production-friendly diagnostics.

9. Dynamic Class-File Constants

What Are They?

Introduces CONSTANT_Dynamic to the constant pool, enabling dynamic computation of constant values.


10. Removal of Deprecated APIs

What Was Removed?

  • java.xml.ws (JAX-WS).
  • java.corba (CORBA).
  • JavaFX (moved to a standalone project).

11. Unicode 10 Support

What Is It?

Adds support for Unicode 10, including new characters and scripts.


12. Enhanced var Usability

What Is It?

Improved local variable type inference, especially in lambda expressions.


13. Performance Enhancements

  • Improved Garbage Collection for better throughput.
  • Optimizations in Thread-Local Handshakes for reduced pause times.

14. Epsilon Garbage Collector

What Is It?

A no-op garbage collector designed for short-lived applications or memory profiling.

Usage

java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC MyApp

15. Improved AArch64 Support

  • Optimizations for ARM64 architectures.

Benefits of Java 11

  1. Long-Term Support: Stability for enterprises.
  2. Modern Features: Aligns Java with contemporary programming trends.
  3. Performance Gains: Improved garbage collection and runtime optimizations.
  4. Productivity: Simplified APIs and enhanced tools.

Disadvantages

  • Requires migration from Java 8 for legacy systems.
  • Removal of features like Nashorn and JAX-WS can disrupt older applications.

Java 11 is a robust release that modernizes Java while maintaining backward compatibility. Understanding these features is essential for leveraging its full potential in development.

Leave a Comment