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:
5954965-80173492f7a44cc1.jpg
Java11 has also been updated from the following locations (below is a screenshot from the official website)
Sogou screenshot 20180928195041.jpg
Sogou screenshot 20180928195105.jpg
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″;
In Java10 we can use var instead of String, and the expression looks like this:
var str=”hello java 10″;
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
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;
Local variable type inference can be generic. In the next example, the Map type, which 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); }
Starting with Java 11, lambda arguments also allow the var keyword:
Predicate<String>predicate = (@Nullable var a)->true;
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());
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);
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()); / / 200
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()); / / 200
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
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
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}
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
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]
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
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(); / / 3
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); }
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 the website to check (https://docs.oracle.com/en/java/javase/11/)