Java 11 Tutorial For Java Developers

Java 11 Tutorial For Java Developers from Coding compilerJava 11 has been available for download since the end of September 2018 and is again a so-called LTS release (long-time support) after Java 8. This is pleasing in that it offers support and updates for a few years, whereas Java 9 and 10 are available through the Oracle’s release policies were only up-to-date for a short period of 6 months and no longer receive any updates. Let’s start learning Java 11.

Java 11 Tutorials

Before we begin, be sure to read the following practice guide to Oracle’s new licensing policy. While Java 10 is more of a cosmetic change, luckily, Java 11 provides a few more new APIs, but I still find the need for the major version to be questionable.

Note: New licensing policy at Oracle

If you plan to distribute your software commercially or do so already, you should consider the new release policy of Oracle when downloading Java 11: The Oracle JDK, which has hitherto always been free of charge, is now chargeable. As an alternative, you can switch to the OpenJDK . During development, the Oracle JDK can still be used free of charge.

Java 11 Syntax Extension for var

In Java 11, a little adaptation was made to the syntax: varNot only is it restricted to local variables, but it can varnow also be used to specify type in lambda expressions. Let’s take a closer look at this below.

Java 11 Local Variable Syntax for Lambda Parameters

Up to and including Java 10, you could either specify all types or omit them in a lambda expression. However, the use of it was varnot possible there. This was changed with Java 11 so that the following lambda expression is now correct:

1
(var x, var y) -> x.doSomething(y)

Let’s take a look back – in Java 10 these two variants were allowed:

1
2
IntFunction<Integer> doubleItTyped = (final int x) -> x * 2;
IntFunction<Integer> doubleItNoType = x -> x * 2;

However, the specification of var:

1
IntFunction<Integer> doubleItWithVar = (var x) -> x * 2;

Why should this variant be useful at all, where you can completely do without the type specification? A valid question! The answer comes from the desire to not have to explicitly specify a type, but nevertheless to be able to define the parameter definitively or to add annotations. Of course, this is not possible if the lambda version is used completely without a type. Here it is possible varto dispense with the explicit type specification, but to be able to provide further information. This is @NonNullclarified by the annotation below :

1
Function<String, String> trimmer = (@NonNull var str) -> str.trim();

Although this adaptation in the syntax is only small, but fine, because more consistency is achieved and – as demonstrated in the example – the possibilities for specifying additional information about a variable is possible.

API Improvements in Java 11

Java 11 new helper methods in the class String and the utility class Files.

In this section we’ll start with the new features in various Java 11 APIs. There are some noteworthy things about API improvements: First, I’ll talk about the new methods in the class java.lang.String

Then I show various convenience functions, first in the utility class java.nio.file.Files. In the following series part I introduce a smaller extension in the class java.util.Optional<T>. Such is also found in the classes java.util.function.Predicate<T>as well as in java.util.concurrent.Time-Unit. I treat both innovations in separate sections. Finally, I introduce the HTTP / 2 API, which left the incubator state with Java 11 and was added to the full-fledged API in the JDK.

Java 11 New helper methods in class String

The java.lang.String class has existed since JDK 1.0 and has since experienced few API changes. This changes with Java 11 – the following methods have been introduced:

  • ISBLANK ()
  • lines ()
  • repeat (int)
  • Strip ()
  • strip leading ()
  • StripTrailingZero ()

Let’s have a look at simple examples for a better understanding.

The isBlank () method

Strings used to be laborious or only external libraries could be used to check if they contained only whitespaces. As a remedy Java 11 introduced the method isBlank()based on Character.isWhitespace(int). The following example demonstrates testing for an empty or whitespace-only string:

private static void isBlankExample()
{
final String exampleText1 = "";
final String exampleText2 = " ";
final String exampleText3 = " \n \t ";
System.out.println(exampleText1.isBlank());
System.out.println(exampleText2.isBlank());
System.out.println(exampleText3.isBlank());
}

All three spend true.

The method lines ()

When processing data from files, it is often necessary to break up information into individual lines. There is about the method Files.lines(Path). However, if the data source is already a string, this functionality did not exist yet. With JDK 11 we find Stringthe method in the class lines(), which Stream<String>returns one and can be used as follows:

private static void linesExample()
{
final String exampleText = "1 This is a\n2 multi line\n" +
"3 text with\n4 four lines!";
final Stream<String> lines = exampleText.lines();
lines.forEach(System.out::println);
}

This method divides the multi-line string into four separate parts, thus outputting:

1 This is a
2 multi line
3 text with
4 four lines!

The method repeat (int)

Every now and then you have to tackle a string several times, so to repeat an existing string n times. For this purpose, own auxiliary methods or those from external libraries were needed. With Java 11 you can use the method instead repeat(int), as the following example shows:

private static void repeatExample()
{
final String star = "*";
System.out.println(star.repeat(30));
final String delimeter = " -*- ";
System.out.println(delimeter.repeat(6));
}

The above method produces these outputs:

1
2
******************************
-*- -*- -*- -*- -*- -*-
Tip: Special casesThe two examples shown above are quite natural. Two things you could ask yourself:

  1. What happens if you pass the value 0? Then an empty string is created.
  2. What happens if you Integer.MAX_VALUErepeat an empty string extremely often, about a million times or even times? Even then, consequently, an empty string is created.

The methods strip () , stripLeading (), and stripTrailing ()

With the new method since JDK 11, strip()leading and trailing whitespaces can be removed from a string. But is not there already the method trim()? Actually yes, but trim()uses a slightly different definition of whitespace. The method strip()is based – as isBlank()– on Character.isWhitespace(int).

The same applies to the two methods stripLeading()and stripTrailing(). The former removes whitespace only at the beginning, the latter only at the end of a string. The following example demonstrates these methods:

private static void stripExample()
{
final String exampleText1 = " abc ";
final String exampleText2 = " \t XYZ \t ";
System.out.println("’" + exampleText1.strip() + "’");
System.out.println("’" + exampleText2.strip() + "’");
System.out.println("’" + exampleText2.stripLeading() + "’");
System.out.println("’" + exampleText2.stripTrailing() + "’");
}

Let’s take a look at the results:

1
2
3
4
’abc’
’XYZ’
’XYZ     ’
’    XYZ’

New helper methods in the utility class Files

Java 11 made it easier to handle strings-related strings. It is now possible to write or read strings in a file. To do this, the utility class has java.nio.file.Filesa few extensions in terms of the methods writeString()and readString()get. The following example shows how to write or read a string, UTF-8 encoding by default:

var destinationPath = Path.of("ExampleFile.txt");
Files.writeString(destinationPath, "1: This is a string to file test\n");
Files.writeString(destinationPath, "2: Second line");
final String line1 = Files.readString(destinationPath);
final String line2 = Files.readString(destinationPath);
System.out.println(line1);
System.out.println(line2);

If you execute this program fragment, you probably expect the two lines written in the file as output, but you get the following output differently:

1
2
2: Second line
2: Second line

How come? The answer is relatively simple: when writing, the mode of overwriting and not appending is not used without surprise. Modify the source code minimally as follows:

Files.writeString(destinationPath, "1: This is a string to file test\n");
Files.writeString(destinationPath, "2: Second line", StandardOpenOption.APPEND);
var line1 = Files.readString(destinationPath);
var line2 = Files.readString(destinationPath);

If we carry out the whole thing again, the edition could surprise again:

1
2
3
4
1: This is a string to file test
2: Second line
1: This is a string to file test
2: Second line

We recognize that now the entire file is read in as a single line. Thus, the arc spans String.lines(), with which we then make the following correction:

var destinationDath = Path.of("AppendExampleFile.txt");
Files.writeString(destinationPath, "1: This is a string to file test\n");
Files.writeString(destinationPath, "2: Second line", StandardOpenOption.APPEND);
var content = Files.readString(destinationPath);
content.lines().forEach(System.out::println);

This will give us the expected output:

1
2
1: This is a string to file test
2: Second line

Java 11 Extensions

An introduction to Extensions in the classes Optional , Predicate & TimeUnit.

The previous part of the series was about the innovations in various APIs of Java 11, especially new methods in the class java.lang.String. In addition, I showed various convenience functions, first in the utility class java.nio.file.Files. In this series part I introduce a smaller extension in the class java.util.Optional<T>. Such is also found in the classes java.util.function.Predicate<T>as well as in java.util.concurrent.Time-Unit. I treat both innovations in separate sections. In the next part, I introduce the HTTP / 2 API, which left the incubator state with Java 11 and was added to the full-fledged API in the JDK.

Extension in class Optional

As mentioned in the text for Java 10, the class represents java.util.Optional<T>a tremendous enrichment of the JDK in Java 8. In both Java 9 and Java 10, the API has been made a little clearer. Finally, in Java 11, isEmpty()another method is added. This brings more consistency to other APIs like those of Collectionand String

The method isEmpty()conforms trueto its name if no value is Optional<T>included, and otherwise false. The improvement in the readability of the source code by omitting the negation illustrates the following example:

final Optional<String> optEmpty = Optional.empty();
if (!optEmpty.isPresent())
    System.out.println("check for empty JDK 10 style");
if (optEmpty.isEmpty())
    System.out.println("check for empty JDK 11 style");

Extension in the class Predicate

The class java.util.function.Predicate<T>has been very useful since Java 8 to define filter conditions for stream processing. In addition to the link with and()and or()was a negation negate()expressed by. It was a bit awkward and difficult to read, as the following example shows:

// JDK 10 style
final Predicate<string> isEmpty = String::isEmpty;
final Predicate<string> notEmptyJdk10 = isEmpty.negate();
</string></string>

For simplicity, one would have not()wished for a method . Java 11 offers one that can be used as follows:

1
2
3
// JDK 11 style
final Predicate<string> notEmptyJdk11 = Predicate.not(String::isEmpty);
</string>

To increase the readability, we recommend that you use static import:

1
import static java.util.function.Predicate.not;

Then one can write the negation more succinctly as follows:

1
2
final Predicate<string> notEmptyJdk11 = not(String::isEmpty);
</string>

In using applications, this leads to a significant increase in readability. Note also that in the introductory example you had to introduce an artificial Explaining Variable so that you could negate it. This is no longer necessary with Java 11.

Extension in class TimeUnit

The class java.util.concurrent.TimeUnithas been extended and now has the method convert(Duration)that allows a conversion of the TimeUnitrepresented time unit into one from the Java 9 introduced Date and Time API:

1
2
3
4
5
final TimeUnit days = TimeUnit.DAYS;
System.out.println(days.convert(Duration.ofDays(7)));
System.out.println(days.convert((Duration.ofHours(72)));
System.out.println(days.convert((Duration.ofHours(42)));

The above program fragment produces the following outputs, which show that the three calls match the time periods in days or hours, as expected:

1
2
3
7
3
1

The next part is about the Java 11 HTTP / 2-API!

Related Java 11 Articles

Related Java Interview Questions

  1. JDBC Interview Questions
  2. Java Servlet Interview Questions
  3. Java IO Interview Questions
  4. Java String Interview Questions
  5. Java Collections Interview Questions
  6. Java Exceptions Interview Questions
  7. Java OOPS Interview Questions
  8. Core Java Interview Questions
  9. JSF Interview Questions
  10. JSP Interview Questions
  11. JPA Interview Questions
  12. Spring Framework Interview Questions
  13. Spring Boot Interview Questions
  14. Core Java Multiple Choice Questions
  15. 60 Java MCQ Questions And Answers
  16. Aricent Java Interview Questions
  17. Accenture Java Interview Questions
  18. Advanced Java Interview Questions For 5 8 10 Years Experienced
  19. Core Java Interview Questions For Experienced

Leave a Reply

Your email address will not be published. Required fields are marked *