Java 11, released in September 2018, is a significant release of the Java platform with several new features and enhancements that improve the language’s productivity, security, and performance. This tutorial will cover some of the most important features introduced in Java 11, along with examples to illustrate their usage.
1. Local-Variable Syntax for Lambda Parameters
Java 11 allows you to use the var
keyword in lambda expressions to infer the type of the parameters, similar to local variables. This feature can make the code more readable and concise when you want to apply annotations or modifiers to parameters.
Example
import java.util.List;
import java.util.stream.Collectors;
public class LambdaVarExample {
public static void main(String[] args) {
List<String> names = List.of("Alice", "Bob", "Charlie");
// Using var in lambda expression
List<String> upperNames = names.stream()
.map((var name) -> name.toUpperCase())
.collect(Collectors.toList());
System.out.println(upperNames);
}
}
2. String
Class Enhancements
Java 11 introduces several new methods in the String
class that make it easier to handle common string operations. These include isBlank()
, strip()
, stripLeading()
, stripTrailing()
, lines()
, and repeat()
.
Example
public class StringEnhancementsExample {
public static void main(String[] args) {
String multilineString = " Hello\n World \n";
// Check if a string is blank
System.out.println("Is blank: " + " ".isBlank()); // true
// Strip leading and trailing whitespace
System.out.println("Strip: '" + " hello ".strip() + "'"); // 'hello'
// Strip leading whitespace
System.out.println("Strip Leading: '" + " hello ".stripLeading() + "'"); // 'hello '
// Strip trailing whitespace
System.out.println("Strip Trailing: '" + " hello ".stripTrailing() + "'"); // ' hello'
// Get lines as a stream
System.out.println("Lines: " + multilineString.lines().collect(Collectors.toList()));
// Repeat a string
System.out.println("Repeat: " + "ha".repeat(3)); // hahaha
}
}
3. New File
Methods
Java 11 adds new methods to the Files
class for reading and writing strings to files efficiently. These include readString()
, writeString()
, and isSameFile()
.
Example
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class FileMethodsExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try {
// Write string to file
Files.writeString(path, "Hello, World!");
// Read string from file
String content = Files.readString(path);
System.out.println("File Content: " + content);
// Check if two paths refer to the same file
Path path2 = Paths.get("example.txt");
boolean isSameFile = Files.isSameFile(path, path2);
System.out.println("Is Same File: " + isSameFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. HTTP Client (Standard)
Java 11 standardizes the new HTTP client API, which was incubated in Java 9 and 10. The new API supports HTTP/2 and WebSocket and provides a more efficient and modern way to handle HTTP requests and responses.
Example
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.build();
// Asynchronous request
CompletableFuture<HttpResponse<String>> responseFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
responseFuture.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join(); // Wait for completion
}
}
5. Optional Enhancements
Java 11 introduces a new method isEmpty()
to the Optional
class, which is the opposite of isPresent()
. This method provides a more readable way to check for the absence of a value.
Example
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optional = Optional.ofNullable(null);
// Check if Optional is empty
if (optional.isEmpty()) {
System.out.println("Optional is empty");
} else {
System.out.println("Optional value: " + optional.get());
}
}
}
6. Predicate.not()
Method
Java 11 adds a static not()
method to the Predicate
interface, which makes negating predicates more concise and readable.
Example
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateNotExample {
public static void main(String[] args) {
List<String> names = List.of("Alice", "", "Bob", "Charlie", "");
// Filter non-empty strings using Predicate.not()
List<String> nonEmptyNames = names.stream()
.filter(Predicate.not(String::isEmpty))
.collect(Collectors.toList());
System.out.println("Non-empty Names: " + nonEmptyNames);
}
}
7. Running Java Files Directly
Java 11 introduced the ability to run a single Java source file directly without the need to compile it explicitly using javac
. This feature is particularly useful for small scripts and quick tests.
Example
Assuming you have a file HelloWorld.java
:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
You can run it directly from the command line:
java HelloWorld.java
This command compiles and runs the Java file in one step.
8. Epsilon Garbage Collector
Java 11 introduces the Epsilon garbage collector, a no-op garbage collector that handles memory allocation but does not reclaim memory. It is useful for performance testing and debugging memory-related issues.
Enabling Epsilon GC
To use the Epsilon GC, you need to specify it as an option when running your Java application:
java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -Xmx512m MyApp
Note: Epsilon GC will not free any memory; your application will eventually run out of memory.
9. Deprecation of Nashorn JavaScript Engine
The Nashorn JavaScript engine, introduced in JDK 8, has been deprecated in Java 11. This move encourages developers to use alternative JavaScript engines or platforms like GraalVM for executing JavaScript code within Java applications.
Conclusion
Java 11 introduces several powerful features and improvements that enhance the language’s capabilities and ease of use. These features improve productivity and make Java more efficient and modern, keeping it relevant in today’s rapidly evolving software development landscape. By understanding and utilizing these features, developers can write cleaner, more efficient, and more maintainable code.