Java 11 introduced several new features and enhancements. Here are some notable features with examples:
- Local-Variable Syntax for Lambda Parameters: Java 11 allows var to be used in lambda parameters, which provides improved readability and conciseness.
Example:
java// Before Java 11
someList.forEach((String item) -> {
System.out.println(item);
});
// With Java 11
someList.forEach((var item) -> {
System.out.println(item);
})
- HTTP Client (Standard API):
Java 11 introduced a new HTTP client API as a replacement for the deprecated
HttpURLConnection
. It provides a more modern and flexible way to send HTTP requests and handle responses.
Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
- Nest-Based Access Control: Java 11 introduced the concept of nest-based access control, allowing access to private members of an outer class from its inner classes and vice versa.
public class OuterClass {
private int outerField = 10;
public class InnerClass {
private int innerField = 20;
public int sum() {
return outerField + innerField;
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.sum()); // Output: 30
}
}
These are just a few examples of the new features introduced in Java 11. Other features include improved performance, Epsilon garbage collector, enhanced security, and more. It's worth noting that Java continues to evolve, and newer versions may introduce additional features and improvements.
Comments
Post a Comment