Signup/Sign In

Java 11 New Features

Java 11 was introduced in September 2018, six months after the release of Java 10. Java 10 was the last Java release that could be used for commercial purposes without a license.

Java 11 is not free, and we need to pay to use it for commercial purposes. Oracle still provides OpenJDK releases that can be used free of cost.

In this tutorial, we learn about the new features introduced in Java 11.

Running Java Files

To run a Java file, we first compile it using the javac command. But with Java 11, we can directly run a Java file by using single java command.

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

We no longer need to use the above process. Instead, we can use the following command and it will give the same results. Read our detailed article on this.

java MyFirstJavaProgram.java

New String Methods

Java 11 introduced a few new methods to the String class. The following list explains these new methods.

isBlank() - this method is used to check whether a string is blank or not. Empty strings and strings with just whitespace are considered blank.

public class Demo
{
	public static void main(String[] args)
	{
		String s1 = "";
		String s2 = "    ";
		String s3 = "String";
		
		System.out.println("s1 is blank: " + s1.isBlank());
		System.out.println("s2 is blank: " + s2.isBlank());
		System.out.print("s3 is blank: " + s3.isBlank());
	}
}


s1 is blank: true
s2 is blank: true
s3 is blank: false

lines() - this method splits a string using line terminators and returns a stream.

import java.util.List;
import java.util.stream.Collectors;

public class Demo
{
	public static void main(String[] args)
	{
		String s = "This\n is\n a\n String";
		
		List<String> listOfLines = s.lines().collect(Collectors.toList());
		System.out.print(listOfLines);
	}
}


[This, is, a, String]

repeat() - this method is used to duplicate or repeat a string.

public class Demo
{
	public static void main(String[] args)
	{
		String s = "String";
		
		System.out.println("String: " + s);
		System.out.println("String repeated twice: " + s.repeat(2));
		System.out.print("String repeated five times: " + s.repeat(5));
	}
}


String: String
String repeated twice: StringString
String repeated five times: StringStringStringStringString

strip(), stripLeading(), stripTrailing() - These methods are used to remove whitespace from the strings. They are very similar to the existing trim() method, but provide Unicode support.

public class Demo
{
	public static void main(String[] args)
	{
		String s = "  string  ";
		System.out.println("$" + s + "$");
		System.out.println("$" + s.strip() + "$");
		System.out.println("$" + s.stripLeading() + "$");
		System.out.println("$" + s.stripTrailing() + "$");
	}
}


$ string $
$string$
$string $
$ string$

Nest Based Access Control

Previous Java versions allowed access of private members to nested classes(nestmates), but we cannot use them with the Reflection API. Java 11 no longer uses bridge methods and provides the getNestHost(), getNestMembers(), and isNestmatOf() methods for the Reflection API.

public class Demo {
    private void privateMethod() {
        System.out.print("Private Method");
    }
    class NestedClass {
        public void callPrivateMethod() {
            privateMethod();
        }
    }
    public static void main(String[] args) {
        System.out.println(Demo.class.isNestmateOf(Demo.NestedClass.class)); //Demo class is nestmate of NestedClass
        System.out.println(Demo.NestedClass.class.isNestmateOf(Demo.class)); //NestedClass is nestmate of Demo class		
        System.out.println(Demo.NestedClass.class.getNestHost()); //Nest host of NestedClass
        System.out.println(Demo.class.getNestMembers()); //Nest host of Demo class		
    }
}


true
true
class Demo
[Ljava.lang.Class;@36baf30c

New File Methods

Java 11 makes it a lot easier to read and write strings. The readString() and writeString() static methods are added to the Files class for this purpose.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Demo
{
	public static void main(String[] args) throws IOException
	{
		Path path = Files.createTempFile("temporaryFile", ".txt");
		//Writing to the file
		Files.writeString(path, "Hello World");
		//Reading from the file
		String s = Files.readString(path);
		System.out.print(s);
	}
}


Hello World

Collection to an Array

The new default toArray() method is used to easily convert a collection to an array of the correct type.

import java.util.ArrayList;
import java.util.Arrays;

public class Demo
{
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>();
		list.add(5);
		list.add(10);
		list.add(15);
		
		Integer[] intArr = list.toArray(Integer[]::new);
		System.out.print(Arrays.toString(intArr));
	}
}


[5, 10, 15]

The not() Method

A static not() method has been added to the Predicate interface in Java 11. As the name suggests, this method is used to negate a Predicate. The not() method can also be used with method references.

Let's use this method to create two predicates that perform opposite tasks.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Demo
{
	public static void main(String[] args) {
		Predicate<String> startWithZ = s -> s.charAt(0) == 'z';
		Predicate<String> doesNotStartWithZ = Predicate.not(startWithZ);
		
		List<String> list = Arrays.asList("za", "zq", "az", "aq", "zz");
		List<String> strsStartingWithZ = list.stream()
                				.filter(startWithZ)
                				.collect(Collectors.toList());
		List<String> strsNotStartingWithZ = list.stream()
				.filter(doesNotStartWithZ)
				.collect(Collectors.toList());
		
		System.out.println(strsStartingWithZ);
		System.out.println(strsNotStartingWithZ);
	}
}


[za, zq, zz]
[az, aq]

HTTP Client

The HTTP Client API was first introduced in Java 9 and was updated in Java 10. It is offered as a standard feature in Java 11 version. The new API has better performance and is compatible with both HTTP/1.1 and HTTP/2. The API also provides support for WebSockets.

Local-Variable Syntax for Lambda

Java 11 adds the support for Local-Variable syntax for lambda expressions. Lambdas can infer the type, but using the var keyword allows us to use annotations like @NotNull or @Nullable with the parameters.

(@NotNull var str) -> "$" + str

Dynamic Class-File Constants

In Java 11, the Java Class-File format supports a new constant pool form called the CONSTANT_Dynamic. This will delegate creation to a bootstrap method. This was introduced to reduce the cost of creating new forms of materializable class-file constants by creating a single new constant-pool form that will be parameterized with appropriate user-defined behavior. This feature greatly enhances the performance.

Improved Aarch64 Intrinsics

An Intrinsic is a function that is handled in some special way by the compiler. They take advantage of the CPU architecture-specific assembly code to improve performance.

Java 11 improved and optimized the existing string and array intrinsic on AArch64(or ARM64) processors. Java 11 also added new intrinsics for sin, cos, and log methods of the java.lang.Math.

Epsilon Garbage Collector

Java 11 introduced a no-operations(No-Op) garbage collector called Epsilon. This is an experimental feature. It is called a No-Op garbage collector because it will allocate memory but will never collect any garbage. We can use it for simulating Out-Of-Memory errors. The following are some of its use cases.

  • Performance testing
  • Memory pressure testing
  • VM interface testing and
  • Extremely short-lived jobs
  • Last-drop latency and throughput improvements

Use the following command to enable the Epsilon GC.

-XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC

Java Flight Recorder

Java Flight Recorder(JFR in short) is used to gather profiling data for an application. It used to be available only for commercial uses, but it is now open-source under OpenJDK 11. We can use it for production applications, as its overhead is minimal(below 1%). It records the data in a JFR file, and we can use the JDK Mission Control tool to analyze the collected information. Use the following command to start a 180 seconds JFR recording and store the data in the demo.jfr file.

-XX:StartFlightRecording=duration=180s,settings=profile,filename=demo.jfr

Deprecated Java EE and CORBA Modules

Some modules of Java EE and COBRA were deprecated in Java 9. They are now completely removed from Java 11. The following packages and tools are no longer a part of Java 11. However, they are still available for use on third-party websites.

  • java.xml.ws
  • java.xml.bind
  • java.activation
  • java.xml.ws.annotation
  • java.corba
  • java.transaction
  • java.se.ee
  • wsgen and wsimport
  • schemagen and xjc
  • idlj, orbd, servertool, and tnamesrv

Removed JMC and JavaFX

JDK will no longer include JDK Mission Control(JMC) and JavaFX modules. They are available for download separately.

Deprecated Modules

The Nashorn JavaScript engine and JJS were deprecated in Java 11. Future versions will probably remove them completely.

The pack200 and unpack200 tools and the Pack200 compression scheme API of java.util.jar are also deprecated.

Other Changes

  • The insecure RC4 stream cipher is replaced with ChaCha20 and ChaCha20-Poly1305 cipher implementation.
  • The Elliptic Curve Diffie-Hellman (ECDH) scheme is replaced with Curve25519 and Curve448 cryptographic key agreement schemes.
  • The Transport Layer Security(TLS) is upgraded to version 1.3 for better security and improved performance.
  • A low-latency scalable garbage collector called Z Garbage Collector (ZGC) was introduced. This is an experimental feature.
  • Unicode 10 brings new code points, characters, symbols, and emojis.

Summary

Java 11 introduced a lot of new changes and features. A few existing features were deprecated or removed completely. In this tutorial, we learned about the changes introduced in Java 11.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.