Java 11 New Features

JavaJavaBeginner
Practice Now

Introduction

Java 11 was released in September 2018, and it introduced many new features and changes to the platform. This lab will guide you through the process of getting started with Java 11 and exploring its new features.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/FileandIOManagementGroup -.-> java/stream("`Stream`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ProgrammingTechniquesGroup -.-> java/lambda("`Lambda`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/FileandIOManagementGroup -.-> java/nio("`NIO`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117465{{"`Java 11 New Features`"}} java/annotation -.-> lab-117465{{"`Java 11 New Features`"}} java/generics -.-> lab-117465{{"`Java 11 New Features`"}} java/inner_classes -.-> lab-117465{{"`Java 11 New Features`"}} java/stream -.-> lab-117465{{"`Java 11 New Features`"}} java/arraylist -.-> lab-117465{{"`Java 11 New Features`"}} java/classes_objects -.-> lab-117465{{"`Java 11 New Features`"}} java/class_methods -.-> lab-117465{{"`Java 11 New Features`"}} java/encapsulation -.-> lab-117465{{"`Java 11 New Features`"}} java/lambda -.-> lab-117465{{"`Java 11 New Features`"}} java/modifiers -.-> lab-117465{{"`Java 11 New Features`"}} java/oop -.-> lab-117465{{"`Java 11 New Features`"}} java/packages_api -.-> lab-117465{{"`Java 11 New Features`"}} java/wrapper_classes -.-> lab-117465{{"`Java 11 New Features`"}} java/nio -.-> lab-117465{{"`Java 11 New Features`"}} java/identifier -.-> lab-117465{{"`Java 11 New Features`"}} java/arrays -.-> lab-117465{{"`Java 11 New Features`"}} java/comments -.-> lab-117465{{"`Java 11 New Features`"}} java/data_types -.-> lab-117465{{"`Java 11 New Features`"}} java/operators -.-> lab-117465{{"`Java 11 New Features`"}} java/output -.-> lab-117465{{"`Java 11 New Features`"}} java/strings -.-> lab-117465{{"`Java 11 New Features`"}} java/variables -.-> lab-117465{{"`Java 11 New Features`"}} java/arrays_methods -.-> lab-117465{{"`Java 11 New Features`"}} java/object_methods -.-> lab-117465{{"`Java 11 New Features`"}} java/string_methods -.-> lab-117465{{"`Java 11 New Features`"}} java/system_methods -.-> lab-117465{{"`Java 11 New Features`"}} end

Setting Up the Environment

First, make sure that the JDK 11 is installed on your system. You can verify it by running the following command in your terminal:

java -version

If Java 11 is not installed, you can download it from the Oracle website or use a package manager like apt-get or yum.

Once the JDK is setup, create a Java file with the following command:

mkdir -p ~/project && cd ~/project
touch MyFirstJavaProgram.java

Now that the Java file has been created, open it in your favorite text editor.

touch MyFirstJavaProgram.java

Running Java Files

Before Java 11, we had to compile a Java file using the javac command and then run it using the java command. With Java 11, we can directly run a Java file using just the java command.

In the MyFirstJavaProgram.java file, add the following code:

public class MyFirstJavaProgram {
    public static void main(String[] args) {
        System.out.println("Hello, Java 11!");
    }
}

Save the file and run it using the following command:

java MyFirstJavaProgram.java

You should see "Hello, Java 11!" printed to the console.

New String Methods

Java 11 introduced some new methods to the String class. In this step, we will explore those new methods.

isBlank() Method

The isBlank() method is used to check whether a string is blank or not. An empty string or a string with just whitespace is considered blank.

In the MyFirstJavaProgram.java file, add the following code:

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.println("s3 is blank: " + s3.isBlank());

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the following output:

s1 is blank: true
s2 is blank: true
s3 is blank: false
strip(), stripLeading(), and stripTrailing() Methods

The strip(), stripLeading(), and stripTrailing() methods are used to remove whitespace from a string. They are similar to the existing trim() method but provide Unicode support.

In the MyFirstJavaProgram.java file, add the following code:

String s = "   String   ";
System.out.println("$" + s + "$");
System.out.println("$" + s.strip() + "$");
System.out.println("$" + s.stripLeading() + "$");
System.out.println("$" + s.stripTrailing() + "$");

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the following output:

$   String   $
$String$
$String   $
$   String$

Nest Based Access Control

Java 11 introduced a new feature that allows us to access private members of a nested class using the Reflection API. In this step, we will explore this new feature.

In the MyFirstJavaProgram.java file, add the following code:

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));
        System.out.println(Demo.NestedClass.class.isNestmateOf(Demo.class));
        System.out.println(Demo.NestedClass.class.getNestHost());
        System.out.println(Arrays.toString(Demo.class.getNestMembers()));
    }
}

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the following output:

true
true
class Demo
[class MyFirstJavaProgram$Demo$NestedClass]

New File Methods

Java 11 introduced some new methods to the Files class that make it easier to read and write strings. In this step, we will explore these new methods.

In the MyFirstJavaProgram.java file, add the following code:

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);
    }
}

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the following output:

Hello World

Collection to an Array

Java 11 introduced a new default toArray() method that makes it easy to convert a collection to an array of the correct type.

In the MyFirstJavaProgram.java file, add the following code:

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));
    }
}

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the following output:

[5, 10, 15]

The not() Method

Java 11 introduced a new not() method in the Predicate interface that is used to negate a predicate. In this step, we will explore this feature.

In the MyFirstJavaProgram.java file, add the following code:

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);
    }
}

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the following output:

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

HTTP Client

The HTTP Client API was introduced in Java 9 and made standard in Java 11. In this step, we will explore how to use the new HTTP Client API.

In the MyFirstJavaProgram.java file, add the following code:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class Demo {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("https://www.google.com"))
                .GET()
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        System.out.println(response.body());
    }
}

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see the HTML code of the Google homepage in the console.

Local-Variable Syntax for Lambda

Java 11 introduced the var keyword to allow us to use local-variable syntax for lambda expressions. In this step, we will explore this new feature.

In the MyFirstJavaProgram.java file, add the following code:

import java.util.function.Predicate;

public class Demo {
    public static void main(String[] args) {
        Predicate<String> startsWithZ = (@NotNull var str) -> str.charAt(0) == 'z';
        System.out.println(startsWithZ.test("zoo"));
    }
}

Save the file and run it using the following command:

javac MyFirstJavaProgram.java
java MyFirstJavaProgram

You should see true printed to the console.

Epsilon Garbage Collector

Java 11 introduced a new experimental feature called the Epsilon garbage collector, which allocates memory but never collects garbage. In this step, we will explore this experimental feature.

In the MyFirstJavaProgram.java file, add the following code:

public class Demo {
    public static void main(String[] args) {
        byte[] b = new byte[1024 * 1024 * 1024];
        System.out.println("Allocated 1GB of memory");
    }
}

Save the file and run it using the following command:

java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC MyFirstJavaProgram.java

You should see "Allocated 1GB of memory" printed to the console, followed by the program exiting with code 0.

Summary

In this lab, you learned about the new features introduced in Java 11, including new String methods, nest based access control, new file methods, and more. You also learned how to use the new HTTP Client API and the Epsilon garbage collector. You should now have a better understanding of Java 11 and its capabilities.

Other Java Tutorials you may like