Theme interaction

Now that Java11 has been released, which version are you stuck with? What do you have to say about the rapid release of the new version?

Oralce officially released Java 11 on September 25, the first long-term release supported since Java 8.

As we all know, none of the previous releases were long-supported, however, it makes sense to release this latest long-supported release.

Java11 also has a number of new features added and, of course, some features removed.

Here are the release dates for the Java version:

Java11 has also been updated from the following locations (below is a screenshot from the official website)

Because Java11 has integrated some of the features of Java9 and Java10 into Java11, let’s take a look at some of the new features.

New syntax and apis introduced in Java 9-11

Local variable type inference

Java 10 has introduced a new keyword, var, that replaces type information when declaring local variables. Local refers to variable declarations within methods.

Before Java 10, you needed to declare a String like this.

String str="hello java 9";

Copy the code

In Java10 we can use var instead of String, and the expression looks like this:

var str="hello java 10";

Copy the code

Variables declared with var are still statically typed. Incompatible types cannot be reassigned to such variables. This code snippet could not compile:

var str="hello java 11";
str=11;  //Incompatible types

Copy the code

Var is also disallowed when the compiler cannot infer the correct variable type. All of the following code examples cause compiler errors:

// Cannot 	 infer type:
var a;
var nothing =null;
var  lambda=()->System.out.prinltn("Pity!");
var method=this::someNethod;

Copy the code

Local variable type inference can be generic. In the next example, the Map <String, List > type can be reduced to a single var keyword to avoid a lot of boilerplate code:

var myList = new ArrayList<Map<String,List<Integer>>>();
for(var current:myList)
{
	//Current is infered to type:Map<String,List<Integer>>
	System.out.println(current);
}

Copy the code

Starting with Java 11, lambda arguments also allow the var keyword:

Predicate<String>predicate = (@Nullable var a)->true;

Copy the code

HTTP Client

Java 9 began to introduce the HttpClient API to handle HTTP requests. Starting with Java 11, the API officially entered the standard library package (Java.net). Let’s explore what we can do with this API.

The new HttpClient can be used synchronously or asynchronously. A synchronous request blocks the current thread. BodyHandlers define the expected type of the response body (for example, string, byte array, or file) :

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

Copy the code

You can also use asynchrony to perform the same request. Calling sendAsync does not block the current thread, but returns CompletableFuture for asynchronous operation.

var request = HttpRequest.newBuilder()
    .uri(URI.create("https://winterbe.com"))
    .build();
var client = HttpClient.newHttpClient();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println);

Copy the code

We can omit.get () because it is the default request method.

The next example sends data to a given URL via POST. Similar to BodyHandler, you use BodyPublishers to define data types such as strings, byte arrays, files, or input streams that are sent as the body of the request:

var request = HttpRequest.newBuilder()
    .uri(URI.create("https://postman-echo.com/post"))
    .header("Content-Type"."text/plain")
    .POST(HttpRequest.BodyPublishers.ofString("Hi there!")) .build(); var client = HttpClient.newHttpClient(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); / / 200Copy the code

The final example demonstrates how authorization can be performed through basic-Auth:

var request = HttpRequest.newBuilder()
    .uri(URI.create("https://postman-echo.com/basic-auth"))
    .build();
var client = HttpClient.newBuilder()
    .authenticator(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("postman"."password".toCharArray()); } }) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); / / 200Copy the code

Collections

Collections like List, Set, and Map have been extended with new methods. List.of creates a new immutable List from the given parameters. List.copyOf creates an immutable copyOf the List.

var list = List.of("A"."B"."C");
var copy = List.copyOf(list);
System.out.println(list == copy);   // true

Copy the code

Because the list is already immutable, you don’t actually need to create a copy of the list instance, so the list and the copy are the same instance. However, if you copy a mutable list, copying does generate a new instance, so there are no side effects when changing the original list:

var list = new ArrayList<String>();
var copy = List.copyOf(list);
System.out.println(list == copy);   // false

Copy the code

To create an immutable map, you don’t have to create a map entry yourself, but pass keys and values as parameters:

var map = Map.of("A", 1, "B", 2);
System.out.println(map);    // {B=2, A=1}

Copy the code

Immutable collections in Java 11 still use the old interface from the Collection API. However, if you try to modify the immutable collection, will throw out the Java. Lang. UnsupportedOperationException. The good news is that if you try to change an immutable set, Intellij IDEA will issue a warning.

Streams

Streams was introduced in Java 8, which added three new methods. Single parameter construction method:

Stream.ofNullable(null)
    .count()   // 0
Copy the code

Add takeWhile and dropWhile methods to release elements from stream:

Stream.of(1, 2, 3, 2, 1) .dropWhile(n -> n < 3) .collect(Collectors.toList()); // [3, 2, 1] Stream.of(1, 2, 3, 2, 1) .takeWhile(n -> n < 3) .collect(Collectors.toList()); / / [1, 2]Copy the code

If you are not familiar with Stream, refer to this article [1].

Optionals

Optionals provides some very convenient features, for example you can now simply convert Optional to Stream, or provide another Optional as a backup for empty Optinal:

Optional.of("foo").orElseThrow();     // foo
Optional.of("foo").stream().count();  // 1
Optional.ofNullable(null)
    .or(() -> Optional.of("fallback"))
    .get();                           // fallback
Copy the code

Strings

Java11 adds some helper methods to String to trim or check for whitespace:

"".isBlank();                // true
" Foo Bar ".strip();          // "Foo Bar"
" Foo Bar ".stripTrailing();  // " Foo Bar"
" Foo Bar ".stripLeading();   // "Foo Bar "
"Java".repeat(3);             // "JavaJavaJava"
"A\nB\nC".lines().count(); / / 3Copy the code

InputStreams

InputStream adds a transferTo method that can be used to transfer data directly to OutputStream:

var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("myFile.txt");
var tempFile = File.createTempFile("myFileCopy"."txt");
try (var outputStream = new FileOutputStream(tempFile)) {
    inputStream.transferTo(outputStream);
}

Copy the code

These new features above just in front of several versions, or some more feel nice new features, if you still want to know more about the new features of can go to see (docs.oracle.com/en/java/jav…

Or check out the link below

  • [for reactive Flow of programming API] : community.oracle.com/docs/DOC-10…
  • [Java module system] : www.oracle.com/corporate/f…
  • [application class data sharing] : blog.codefx.org/java/applic…
  • [constant dynamic class file] : openjdk.java.net/jeps/309
  • [Java REPL (JShell)] : docs.oracle.com/javase/10/j…
  • [flight recorder] : openjdk.java.net/jeps/328
  • [10] Unicode: openjdk.java.net/jeps/327
  • [G1: completely parallel garbage collector] : blog.idrsolutions.com/2018/04/jav…
  • [ZGC: scalable low-latency garbage collector] : openjdk.java.net/jeps/333
  • [Epsilon: No – Op the garbage collector] : openjdk.java.net/jeps/318
  • [deprecated Nashorn JavaScript engine] : openjdk.java.net/jeps/335
References:
  • Docs.oracle.com/en/java/jav…
  • Openjdk.java.net/projects/jd…
  • Winterbe.com/posts/2018/…
  • www.oracle.com/technetwork…

Please scan the qr code below to follow our wechat official account and push fresh information every day!

Pay attention to wechat public number “learn Java well”, dry goods updated every day!