Java 11 - Quick Guide



Java 14 - Overview

Java 11 is the first LTS , Long Term Support feature release after Java 8. It followed the Java release cadence introduced Java 10 onwards and it was released on Sept 2018, just six months after Java 10 release.

Java 9 and Java 10 are non-LTS release. Java 11 release is a LTS release.

New Features

Following are the major new features which are introduced in Java 11.

  • JEP 321 − HTTP Client API standardized.

  • JEP 330 − Launch Single-File Source-Code Programs without compilation

  • JEP 323 − Local-Variable Syntax for Lambda Parameters

  • JEP 181 − Nest-Based Access Control

  • JEP 331 − Low-Overhead Heap Profiling

  • JEP 318 − Epsilon, A No-Op Garbage Collector

  • JEP 333 − ZGC A Scalable Low-Latency Garbage Collector

  • Collection API Updates − New Collection.toArray(IntFunction) Default Method.

  • String API Updates − New methods added like repeat(), isBlank(), strip() and lines().

  • Files API Updates − New methods added like readString(), and writeString().

  • Optional Updates − New method added, isEmpty().

Java 11 enhanced numerous APIs with new methods and options and removed deprecated APIs and options. We'll see these changes in next chapters.

Java 11 - Environment Setup

Live Demo Option Online

We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

Try the following example using Live Demo option available at the top right corner of the below sample code box −

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

For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.

Local Environment Setup

If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.

Java SE is available for download for free. To download click here, please download a version compatible with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way

    C:\Windows\System32;c:\Program Files\java\jdk\bin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Edit the 'C:\autoexec.bat' file and add the following line at the end −

    SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc

    export PATH=/path/to/java:$PATH'

Popular Java Editors

To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.

  • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org.

IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

Java 11 - Standard HttpClient

An enhanced HttpClient API was introduced in Java 9 as an experimental feature. With Java 11, now HttpClient is a standard. It is recommended to use instead of other HTTP Client APIs like Apache Http Client API. It is quite feature rich and now Java based applications can make HTTP requests without using any external dependency.

Steps

Following are the steps to use an HttpClient.

  • Create HttpClient instance using HttpClient.newBuilder() instance

  • Create HttpRequest instance using HttpRequest.newBuilder() instance

  • Make a request using httpClient.send() and get a response object.

Example

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class APITester {
   public static void main(String[] args) {
      HttpClient httpClient = HttpClient.newBuilder()
         .version(HttpClient.Version.HTTP_2)
         .connectTimeout(Duration.ofSeconds(10))
         .build(); 
         try {
            HttpRequest request = HttpRequest.newBuilder()
            .GET()
            .uri(URI.create("https://www.google.com"))
            .build();                              
            HttpResponse<String> response = httpClient.send(request,
            HttpResponse.BodyHandlers.ofString()); 

         System.out.println("Status code: " + response.statusCode());                            
         System.out.println("Headers: " + response.headers().allValues("content-type"));
         System.out.println("Body: " + response.body());
      } catch (IOException | InterruptedException e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following output.

Status code: 200
Headers: [text/html; charset=ISO-8859-1]
Body: <!doctype html>
...
</html>

Java 11 - Compile free Launch

Java 11 onwards, now a single java file can be tested easily without compiling as well. Consider the following example −

ApiTester.java

public class Tester {
   public static void main(String[] args) {
     System.out.println("Hello World!"); 
   }
}

Old way of running file

$ javac ApiTester.java
$ java Tester
Hello World!

New way of running file

$ java ApiTester.java
Hello World!

This new feature will help developer to quick test a functionality without need to compile before running a code.

Java 11 - String API

Java 11 introduced multiple enhancements to String.

  • String.repeat(int) − Repeats a string given number of times. Returns the concatenated string.

  • String.isBlank() − Checks if a string is empty or have white spaces only.

  • String.strip() − Removes the leading and trailing whitespaces.

  • String.stripLeading() − Removes the leading whitespaces.

  • String.stripTrailing() − Removes the trailing whitespaces.

  • String.lines() − Return the stream of lines of multi-line string.

Consider the following example −

ApiTester.java

import java.util.ArrayList;
import java.util.List;

public class APITester {
   public static void main(String[] args) {
      String sample = " abc ";
      System.out.println(sample.repeat(2)); // " abc  abc "
      System.out.println(sample.isBlank()); // false
      System.out.println("".isBlank()); // true
      System.out.println("   ".isBlank()); // true
      System.out.println(sample.strip()); // "abc"
      System.out.println(sample.stripLeading()); // "abc "
      System.out.println(sample.stripTrailing()); // " abc"
      sample = "This\nis\na\nmultiline\ntext.";

      List<String> lines = new ArrayList<>();

      sample.lines().forEach(line -> lines.add(line));
      lines.forEach(line -> System.out.println(line));
   }
}

Output

abc  abc 
false
true
true
abc
abc 
 abc
This
is
a
multiline
text.

Java 11 - Collections to Array

Java 11 introduced an easy way to convert a collection to an array.

Old Way

nameArray = nameList.toArray(new String[nameList.size()]);

New Way

nameArray = nameList.toArray(String[]::new);

Consider the following example −

ApiTester.java

import java.util.Arrays;
import java.util.List;

public class APITester {
   public static void main(String[] args) {		
      List<String> namesList = Arrays.asList("Joe", "Julie");
      // Old way
      String[] names = namesList.toArray(new String[namesList.size()]);
      System.out.println(names.length);
      // New way
      names = namesList.toArray(String[]::new);
      System.out.println(names.length);
   }
}

Output

2
2

Java 11 - File APIs

Java 11 introduced an easy way to read and write files by providing new overloaded methods without writing much boiler plate code.

Consider the following example −

ApiTester.java

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class APITester {
   public static void main(String[] args) {		
      try {
         Path tempFilePath = Files.writeString(
            Path.of(File.createTempFile("tempFile", ".tmp").toURI()),
            "Welcome to TutorialsPoint", 
            Charset.defaultCharset(), StandardOpenOption.WRITE);

         String fileContent = Files.readString(tempFilePath);

         System.out.println(fileContent);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Welcome to TutorialsPoint

Java 11 - Optional Class

Java 11 introduced new method to Optional class as isEmpty() to check if value is present. isEmpty() returns false if value is present otherwise true.

It can be used as an alternative of isPresent() method which often needs to negate to check if value is not present.

Consider the following example −

ApiTester.java

import java.util.Optional;

public class APITester {
   public static void main(String[] args) {		
      String name = null;

      System.out.println(!Optional.ofNullable(name).isPresent());
      System.out.println(Optional.ofNullable(name).isEmpty());

      name = "Joe";
      System.out.println(!Optional.ofNullable(name).isPresent());
      System.out.println(Optional.ofNullable(name).isEmpty());
   }
}

Output

true
true
false
false

Java 11 - Not Predicate

Java 11 introduced new method to Predicate interface as not() to negate an existing predicate similar to negate method.

Consider the following example −

ApiTester.java

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

public class APITester {
   public static void main(String[] args) {		
      List<String> tutorialsList = Arrays.asList("Java", "\n", "HTML", " ");

      List<String> tutorials = tutorialsList.stream()
         .filter(Predicate.not(String::isBlank))
         .collect(Collectors.toList());

      tutorials.forEach(tutorial -> System.out.println(tutorial));
   }
}

Output

Java
HTML

Java 11 - Var in Lambda

Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.

(@NonNull var value1, @Nullable var value2) -> value1 + value2

Consider the following example −

ApiTester.java

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

@interface NonNull {}

public class APITester {
   public static void main(String[] args) {		
      List<String> tutorialsList = Arrays.asList("Java", "HTML");

      String tutorials = tutorialsList.stream()
         .map((@NonNull var tutorial) -> tutorial.toUpperCase())
         .collect(Collectors.joining(", "));

      System.out.println(tutorials);
   }
}

Output

Java
HTML

Limitations

There are certain limitations on using var in lambda expressions.

  • var parameters cannot be mixed with other parameters. Following will throw compilation error.

(var v1, v2) -> v1 + v2
  • var parameters cannot be mixed with other typed parameters. Following will throw compilation error.

(var v1, String v2) -> v1 + v2
  • var parameters can only be used with parenthesis. Following will throw compilation error.

var v1 -> v1.toLowerCase()

Java 11 - Nested Based Access

Java 11 introduced a concept of nested class where we can declare a class within a class. This nesting of classes allows to logically group the classes to be used in one place, making them more readable and maintainable. Nested class can be of four types −

  • Static nested classes

  • Non-static nested classes

  • Local classes

  • Anonymous classes

Java 11 also provide the concept of nestmate to allow communication and verification of nested classes.

Consider the following example −

ApiTester.java

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class APITester {
   public static void main(String[] args) {		
      boolean isNestMate = APITester.class.isNestmateOf(APITester.Inner.class);
      boolean nestHost = APITester.Inner.class.getNestHost() == APITester.class;

      System.out.println(isNestMate);
      System.out.println(nestHost);

      Set<String> nestedMembers = Arrays.stream(APITester.Inner.class.getNestMembers())
         .map(Class::getName)
         .collect(Collectors.toSet());
      System.out.println(nestedMembers);
   }
   public class Inner{}
}

Output

true
true
[APITester$Inner, APITester]

Java 11 - Removed/Deprecated APIs

Java 11 has removed selected deprecated APIs. Following is the list of removed APIs.

Java EE and CORBA

Following deprecated Java EE and CORBA are removed from Java 11 release.

  • Java API for XML-Based Web Services (java.xml.ws)

  • Java Architecture for XML Binding (java.xml.bind)

  • JavaBeans Activation Framework (java.activation)

  • Common Annotations (java.xml.ws.annotation)

  • Common Object Request Broker Architecture (java.corba)

  • JavaTransaction API (java.transaction)

These APIs are available as standalone versions of third party site.

JMC and JavaFX

  • JDK Mission Control (JMC) is removed from standard JDK. It is available as standalone download.

  • JavaFX is also removed from standard JDK. It is available as separate module to download.

Deprecated Modules

  • Nashorn JavaScript engine along with JJS tool is deprecated.

  • Pack200 compression scheme for JAR files is deprecated.

Advertisements