Sitemap

Java 11 features

4 min readMar 27, 2023

--

Press enter or click to view image in full size
Photo by Mia Golic on Unsplash

Java 11 is the latest long-term support (LTS) version of Java programming language, which was released on September 25, 2018. Java 11 includes several new features and improvements that aim to enhance the security, performance, and functionality of the language. In this article, we will explore some of the most notable Java 11 features in simple terms and with examples.

1. Local-Variable Syntax for Lambda Parameters

One of the most significant changes introduced in Java 11 is the ability to use the var keyword in lambda expressions. This feature allows you to declare lambda parameters using var instead of explicitly declaring their type.

Consider the following example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach((var number) -> {
System.out.println(number);
});

In this example, we declare a List of integers and then use the forEach method to iterate over the list. We also use a lambda expression to print each number in the list. In Java 8 or earlier, we would have to declare the type of the lambda parameter explicitly, like this:

numbers.forEach((Integer number) -> {
System.out.println(number);
});

2. HTTP Client

Java 11 includes a new HTTP client API that provides a more modern and efficient way to send HTTP requests and receive responses. The new HTTP client API supports both HTTP/1.1 and HTTP/2 protocols and includes features like HTTP/2 push, server push, and WebSocket. The new API is also asynchronous and non-blocking, making it more scalable and performant than the previous HttpURLConnection API.

Here’s an example of using the new HTTP client API to send a GET request and receive a response:

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

In this example, we create a new HttpClient instance and use it to send a GET request to the specified URL. We then use the HttpResponse.BodyHandlers class to specify that we want to receive the response body as a String. Finally, we print the response body to the console.

3. New String Methods

A couple of new methods to the String class were introduced.

1. isBlank(). It checks whether a string is empty or contains only white spaces.

String str1 = "";
String str2 = " ";
String str3 = "Hello World";
System.out.println(str1.isBlank()); // Output: true
System.out.println(str2.isBlank()); // Output: true
System.out.println(str3.isBlank()); // Output: false

2. strip(). It removes white spaces from both the beginning and the end of a string. This method is similar to the trim() method, but it is more powerful because it can handle Unicode white spaces.

String str1 = "  Hello World  ";
String str2 = "\u2005Hello World\u2005";
System.out.println(str1.strip()); // Output: "Hello World"
System.out.println(str2.strip()); // Output: "Hello World"

4. Nest-Based Access Control

Java 11 introduced a new access control feature called nest-based access control. This feature allows classes that are logically part of the same code entity to access each other’s private members, without the need for setters and getters.

Get Himani Prasad’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s an example:

class Outer {
private int x;
class Inner {
void setX(int x) {
Outer.this.x = x;
}
}
}

In the example above, the Inner class can access the private member x of the Outer class, even though it is not defined in the Inner class itself.

5. Single-File Source Code Programs

We can execute the file directly without the need for a separate compilation step. The Java interpreter will compile the code and execute the program in one step.

public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
java Main.java

Before Java 11, this program would need to be compiled into a class file using the javac command and then executed using the java command.

javac HelloWorld.java
java Main.java

6. ZGC (Experimental)

ZGC (Z Garbage Collector) is an experimental feature. It is a scalable, low-latency garbage collector designed to work with large heaps. The goal of ZGC is to provide consistent pause times regardless of the heap size.

Before ZGC, the default GC in Java was the G1 garbage collector, which could lead to unpredictable pause times and was not designed to work with very large heaps.

ZGC is a concurrent garbage collector, which means that it can run concurrently with the application threads. This allows the garbage collector to do its work without stopping the application, which reduces pause times. ZGC also uses a compacting algorithm, which moves live objects to contiguous memory blocks, reducing heap fragmentation.

Here’s an example of how to enable ZGC in a Java program:

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

Prior to Java 11, G1 (Garbage First) was the default garbage collector in Java. G1 is also designed for large heap sizes, but it does not have the same low pause time guarantees as ZGC. G1 has been available since Java 7 and can be enabled with the following options:

java -XX:+UseG1GC MyApp

7. ChaCha20 and Poly1305 Cryptographic Algorithms

I don’t know much about these algorithms, here are some articles which provider better and elaborate information: Mkyong.com , Java Interview Point

These algorithms are designed to be fast, secure, and resistant to side-channel attacks.

ChaCha20 is a stream cipher, meaning it encrypts data one byte at a time. It was designed by Daniel J. Bernstein as a faster and more secure alternative to other stream ciphers like RC4. It is widely used in various applications including TLS, SSH, and VPNs.

Poly1305, on the other hand, is a message authentication code (MAC) algorithm. It is used to provide authenticity and integrity for data, meaning that it can detect any unauthorized changes to the data. It was also designed by Daniel J. Bernstein as a faster and more secure alternative to other MAC algorithms like HMAC.

When used together, ChaCha20 and Poly1305 provide what is called an “authenticated encryption with associated data” (AEAD) scheme. This means that they provide both encryption and authentication for data, as well as the ability to include additional metadata (known as associated data) that is authenticated but not encrypted.

buy me a coffee ☕️: https://www.buymeacoffee.com/himaniprasad.

--

--